Bring STM32F4/F7 together

This commit is contained in:
Scott Lahteine
2019-07-09 23:54:34 -05:00
parent cf9ac4c847
commit ad1c061e7b
49 changed files with 197 additions and 1905 deletions

View File

@@ -0,0 +1,130 @@
/**
* Marlin 3D Printer Firmware
*
* Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
* Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com
* Copyright (c) 2015-2016 Nico Tonnhofer wurstnase.reprap@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#if defined(STM32GENERIC) && defined(STM32F7)
#include "../HAL.h"
#include "HAL_timers_STM32F7.h"
// ------------------------
// Local defines
// ------------------------
#define NUM_HARDWARE_TIMERS 2
//#define PRESCALER 1
// ------------------------
// Private Variables
// ------------------------
tTimerConfig timerConfig[NUM_HARDWARE_TIMERS];
// ------------------------
// Public functions
// ------------------------
bool timers_initialized[NUM_HARDWARE_TIMERS] = { false };
void HAL_timer_start(const uint8_t timer_num, const uint32_t frequency) {
if (!timers_initialized[timer_num]) {
switch (timer_num) {
case STEP_TIMER_NUM:
//STEPPER TIMER TIM5 //use a 32bit timer
__HAL_RCC_TIM5_CLK_ENABLE();
timerConfig[0].timerdef.Instance = TIM5;
timerConfig[0].timerdef.Init.Prescaler = (STEPPER_TIMER_PRESCALE);
timerConfig[0].timerdef.Init.CounterMode = TIM_COUNTERMODE_UP;
timerConfig[0].timerdef.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
timerConfig[0].IRQ_Id = TIM5_IRQn;
timerConfig[0].callback = (uint32_t)TC5_Handler;
HAL_NVIC_SetPriority(timerConfig[0].IRQ_Id, 1, 0);
SET_OUTPUT(STEPPER_ENABLE_PIN);
WRITE(STEPPER_ENABLE_PIN);
break;
case TEMP_TIMER_NUM:
//TEMP TIMER TIM7 // any available 16bit Timer (1 already used for PWM)
__HAL_RCC_TIM7_CLK_ENABLE();
timerConfig[1].timerdef.Instance = TIM7;
timerConfig[1].timerdef.Init.Prescaler = (TEMP_TIMER_PRESCALE);
timerConfig[1].timerdef.Init.CounterMode = TIM_COUNTERMODE_UP;
timerConfig[1].timerdef.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
timerConfig[1].IRQ_Id = TIM7_IRQn;
timerConfig[1].callback = (uint32_t)TC7_Handler;
HAL_NVIC_SetPriority(timerConfig[1].IRQ_Id, 2, 0);
break;
}
timers_initialized[timer_num] = true;
}
timerConfig[timer_num].timerdef.Init.Period = (((HAL_TIMER_RATE) / timerConfig[timer_num].timerdef.Init.Prescaler) / frequency) - 1;
if (HAL_TIM_Base_Init(&timerConfig[timer_num].timerdef) == HAL_OK)
HAL_TIM_Base_Start_IT(&timerConfig[timer_num].timerdef);
}
//forward the interrupt
extern "C" void TIM5_IRQHandler() {
((void(*)(void))timerConfig[0].callback)();
}
extern "C" void TIM7_IRQHandler() {
((void(*)(void))timerConfig[1].callback)();
}
void HAL_timer_set_compare(const uint8_t timer_num, const uint32_t compare) {
__HAL_TIM_SetAutoreload(&timerConfig[timer_num].timerdef, compare);
}
void HAL_timer_enable_interrupt(const uint8_t timer_num) {
HAL_NVIC_EnableIRQ(timerConfig[timer_num].IRQ_Id);
}
void HAL_timer_disable_interrupt(const uint8_t timer_num) {
HAL_NVIC_DisableIRQ(timerConfig[timer_num].IRQ_Id);
// We NEED memory barriers to ensure Interrupts are actually disabled!
// ( https://dzone.com/articles/nvic-disabling-interrupts-on-arm-cortex-m-and-the )
__DSB();
__ISB();
}
hal_timer_t HAL_timer_get_compare(const uint8_t timer_num) {
return __HAL_TIM_GetAutoreload(&timerConfig[timer_num].timerdef);
}
uint32_t HAL_timer_get_count(const uint8_t timer_num) {
return __HAL_TIM_GetCounter(&timerConfig[timer_num].timerdef);
}
void HAL_timer_isr_prologue(const uint8_t timer_num) {
if (__HAL_TIM_GET_FLAG(&timerConfig[timer_num].timerdef, TIM_FLAG_UPDATE) == SET) {
__HAL_TIM_CLEAR_FLAG(&timerConfig[timer_num].timerdef, TIM_FLAG_UPDATE);
}
}
bool HAL_timer_interrupt_enabled(const uint8_t timer_num) {
const uint32_t IRQ_Id = uint32_t(timerConfig[timer_num].IRQ_Id);
return NVIC->ISER[IRQ_Id >> 5] & _BV32(IRQ_Id & 0x1F);
}
#endif // STM32GENERIC && STM32F7

View File

@@ -0,0 +1,97 @@
/**
* Marlin 3D Printer Firmware
*
* Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
* Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com
* Copyright (c) 2017 Victor Perez
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <stdint.h>
// ------------------------
// Defines
// ------------------------
#define FORCE_INLINE __attribute__((always_inline)) inline
#define hal_timer_t uint32_t // TODO: One is 16-bit, one 32-bit - does this need to be checked?
#define HAL_TIMER_TYPE_MAX 0xFFFF
#define HAL_TIMER_RATE (HAL_RCC_GetSysClockFreq() / 2) // frequency of timer peripherals
#define STEP_TIMER_NUM 0 // index of timer to use for stepper
#define TEMP_TIMER_NUM 1 // index of timer to use for temperature
#define PULSE_TIMER_NUM STEP_TIMER_NUM
#define TEMP_TIMER_FREQUENCY 1000 // temperature interrupt frequency
#define TEMP_TIMER_PRESCALE 1000 // prescaler for setting Temp timer, 72Khz
#define STEPPER_TIMER_PRESCALE 54 // was 40,prescaler for setting stepper timer, 2Mhz
#define STEPPER_TIMER_RATE (HAL_TIMER_RATE / STEPPER_TIMER_PRESCALE) // frequency of stepper timer
#define STEPPER_TIMER_TICKS_PER_US ((STEPPER_TIMER_RATE) / 1000000) // stepper timer ticks per µs
#define PULSE_TIMER_RATE STEPPER_TIMER_RATE // frequency of pulse timer
#define PULSE_TIMER_PRESCALE STEPPER_TIMER_PRESCALE
#define PULSE_TIMER_TICKS_PER_US STEPPER_TIMER_TICKS_PER_US
#define ENABLE_STEPPER_DRIVER_INTERRUPT() HAL_timer_enable_interrupt(STEP_TIMER_NUM)
#define DISABLE_STEPPER_DRIVER_INTERRUPT() HAL_timer_disable_interrupt(STEP_TIMER_NUM)
#define ENABLE_TEMPERATURE_INTERRUPT() HAL_timer_enable_interrupt(TEMP_TIMER_NUM)
#define DISABLE_TEMPERATURE_INTERRUPT() HAL_timer_disable_interrupt(TEMP_TIMER_NUM)
#define STEPPER_ISR_ENABLED() HAL_timer_interrupt_enabled(STEP_TIMER_NUM)
#define TEMP_ISR_ENABLED() HAL_timer_interrupt_enabled(TEMP_TIMER_NUM)
// TODO change this
extern void TC5_Handler();
extern void TC7_Handler();
#define HAL_STEP_TIMER_ISR() void TC5_Handler()
#define HAL_TEMP_TIMER_ISR() void TC7_Handler()
// ------------------------
// Types
// ------------------------
typedef struct {
TIM_HandleTypeDef timerdef;
IRQn_Type IRQ_Id;
uint32_t callback;
} tTimerConfig;
// ------------------------
// Public Variables
// ------------------------
//extern const tTimerConfig timerConfig[];
// ------------------------
// Public functions
// ------------------------
void HAL_timer_start(const uint8_t timer_num, const uint32_t frequency);
void HAL_timer_enable_interrupt(const uint8_t timer_num);
void HAL_timer_disable_interrupt(const uint8_t timer_num);
bool HAL_timer_interrupt_enabled(const uint8_t timer_num);
void HAL_timer_set_compare(const uint8_t timer_num, const uint32_t compare);
hal_timer_t HAL_timer_get_compare(const uint8_t timer_num);
uint32_t HAL_timer_get_count(const uint8_t timer_num);
void HAL_timer_isr_prologue(const uint8_t timer_num);
#define HAL_timer_isr_epilogue(TIMER_NUM)

View File

@@ -0,0 +1,27 @@
# This HAL is for the STM32F765 board "The Borg" used with STM32Generic Arduino core by danieleff.
# Original core is located at:
https://github.com/danieleff/STM32GENERIC
but I haven't committed the changes needed for the Borg there yet, so please use:
https://github.com/Spawn32/STM32GENERIC
Unzip it into [Arduino]/hardware folder
Download the latest GNU ARM Embedded Toolchain:
https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads
(The one in Arduino doesn't support STM32F7).
Change compiler.path in platform.txt to point to the one you downloaded.
# This HAL is in development.
# Currently only tested on "The Borg".
You will also need the latest Arduino 1.9.0-beta or newer.
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.

View File

@@ -0,0 +1,898 @@
/**
* TMC26XStepper.cpp - - TMC26X Stepper library for Wiring/Arduino
*
* based on the stepper library by Tom Igoe, et. al.
*
* Copyright (c) 2011, Interactive Matter, Marcus Nowotny
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if defined(STM32GENERIC) && defined(STM32F7)
#include "../../../inc/MarlinConfigPre.h"
#if HAS_DRIVER(TMC2660)
#include <stdbool.h>
#include <SPI.h>
#include "TMC2660.h"
#include "../../../inc/MarlinConfig.h"
#include "../../../Marlin.h"
#include "../../../module/stepper_indirection.h"
#include "../../../module/printcounter.h"
#include "../../../libs/duration_t.h"
#include "../../../libs/hex_print_routines.h"
//some default values used in initialization
#define DEFAULT_MICROSTEPPING_VALUE 32
//TMC26X register definitions
#define DRIVER_CONTROL_REGISTER 0x0ul
#define CHOPPER_CONFIG_REGISTER 0x80000ul
#define COOL_STEP_REGISTER 0xA0000ul
#define STALL_GUARD2_LOAD_MEASURE_REGISTER 0xC0000ul
#define DRIVER_CONFIG_REGISTER 0xE0000ul
#define REGISTER_BIT_PATTERN 0xFFFFFul
//definitions for the driver control register
#define MICROSTEPPING_PATTERN 0xFul
#define STEP_INTERPOLATION 0x200ul
#define DOUBLE_EDGE_STEP 0x100ul
#define VSENSE 0x40ul
#define READ_MICROSTEP_POSTION 0x0ul
#define READ_STALL_GUARD_READING 0x10ul
#define READ_STALL_GUARD_AND_COOL_STEP 0x20ul
#define READ_SELECTION_PATTERN 0x30ul
//definitions for the chopper config register
#define CHOPPER_MODE_STANDARD 0x0ul
#define CHOPPER_MODE_T_OFF_FAST_DECAY 0x4000ul
#define T_OFF_PATTERN 0xFul
#define RANDOM_TOFF_TIME 0x2000ul
#define BLANK_TIMING_PATTERN 0x18000ul
#define BLANK_TIMING_SHIFT 15
#define HYSTERESIS_DECREMENT_PATTERN 0x1800ul
#define HYSTERESIS_DECREMENT_SHIFT 11
#define HYSTERESIS_LOW_VALUE_PATTERN 0x780ul
#define HYSTERESIS_LOW_SHIFT 7
#define HYSTERESIS_START_VALUE_PATTERN 0x78ul
#define HYSTERESIS_START_VALUE_SHIFT 4
#define T_OFF_TIMING_PATERN 0xFul
//definitions for cool step register
#define MINIMUM_CURRENT_FOURTH 0x8000ul
#define CURRENT_DOWN_STEP_SPEED_PATTERN 0x6000ul
#define SE_MAX_PATTERN 0xF00ul
#define SE_CURRENT_STEP_WIDTH_PATTERN 0x60ul
#define SE_MIN_PATTERN 0xFul
//definitions for StallGuard2 current register
#define STALL_GUARD_FILTER_ENABLED 0x10000ul
#define STALL_GUARD_TRESHHOLD_VALUE_PATTERN 0x17F00ul
#define CURRENT_SCALING_PATTERN 0x1Ful
#define STALL_GUARD_CONFIG_PATTERN 0x17F00ul
#define STALL_GUARD_VALUE_PATTERN 0x7F00ul
//definitions for the input from the TMC2660
#define STATUS_STALL_GUARD_STATUS 0x1ul
#define STATUS_OVER_TEMPERATURE_SHUTDOWN 0x2ul
#define STATUS_OVER_TEMPERATURE_WARNING 0x4ul
#define STATUS_SHORT_TO_GROUND_A 0x8ul
#define STATUS_SHORT_TO_GROUND_B 0x10ul
#define STATUS_OPEN_LOAD_A 0x20ul
#define STATUS_OPEN_LOAD_B 0x40ul
#define STATUS_STAND_STILL 0x80ul
#define READOUT_VALUE_PATTERN 0xFFC00ul
#define CPU_32_BIT
//default values
#define INITIAL_MICROSTEPPING 0x3ul //32th microstepping
SPIClass SPI_6(SPI6, SPI6_MOSI_PIN, SPI6_MISO_PIN, SPI6_SCK_PIN);
#define STEPPER_SPI SPI_6
//debuging output
//#define TMC_DEBUG1
uint8_t current_scaling = 0;
/**
* Constructor
* number_of_steps - the steps per rotation
* cs_pin - the SPI client select pin
* dir_pin - the pin where the direction pin is connected
* step_pin - the pin where the step pin is connected
*/
TMC26XStepper::TMC26XStepper(const int16_t in_steps, int16_t cs_pin, int16_t dir_pin, int16_t step_pin, uint16_t current, uint16_t resistor) {
// We are not started yet
started = false;
// By default cool step is not enabled
cool_step_enabled = false;
// Save the pins for later use
this->cs_pin = cs_pin;
this->dir_pin = dir_pin;
this->step_pin = step_pin;
// Store the current sense resistor value for later use
this->resistor = resistor;
// Initizalize our status values
this->steps_left = 0;
this->direction = 0;
// Initialize register values
driver_control_register_value = DRIVER_CONTROL_REGISTER | INITIAL_MICROSTEPPING;
chopper_config_register = CHOPPER_CONFIG_REGISTER;
// Setting the default register values
driver_control_register_value = DRIVER_CONTROL_REGISTER|INITIAL_MICROSTEPPING;
microsteps = _BV(INITIAL_MICROSTEPPING);
chopper_config_register = CHOPPER_CONFIG_REGISTER;
cool_step_register_value = COOL_STEP_REGISTER;
stallguard2_current_register_value = STALL_GUARD2_LOAD_MEASURE_REGISTER;
driver_configuration_register_value = DRIVER_CONFIG_REGISTER | READ_STALL_GUARD_READING;
// Set the current
setCurrent(current);
// Set to a conservative start value
setConstantOffTimeChopper(7, 54, 13,12,1);
// Set a nice microstepping value
setMicrosteps(DEFAULT_MICROSTEPPING_VALUE);
// Save the number of steps
number_of_steps = in_steps;
}
/**
* start & configure the stepper driver
* just must be called.
*/
void TMC26XStepper::start() {
#ifdef TMC_DEBUG1
SERIAL_ECHOLNPGM("\n TMC26X stepper library");
SERIAL_ECHOPAIR("\n CS pin: ", cs_pin);
SERIAL_ECHOPAIR("\n DIR pin: ", dir_pin);
SERIAL_ECHOPAIR("\n STEP pin: ", step_pin);
SERIAL_PRINTF("\n current scaling: %d", current_scaling);
SERIAL_PRINTF("\n Resistor: %d", resistor);
//SERIAL_PRINTF("\n current: %d", current);
SERIAL_ECHOPAIR("\n Microstepping: ", microsteps);
#endif
//set the pins as output & its initial value
pinMode(step_pin, OUTPUT);
pinMode(dir_pin, OUTPUT);
pinMode(cs_pin, OUTPUT);
//SET_OUTPUT(STEPPER_ENABLE_PIN);
extDigitalWrite(step_pin, LOW);
extDigitalWrite(dir_pin, LOW);
extDigitalWrite(cs_pin, HIGH);
STEPPER_SPI.begin();
STEPPER_SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE3));
//set the initial values
send262(driver_control_register_value);
send262(chopper_config_register);
send262(cool_step_register_value);
send262(stallguard2_current_register_value);
send262(driver_configuration_register_value);
//save that we are in running mode
started = true;
}
/**
* Mark the driver as unstarted to be able to start it again
*/
void TMC26XStepper::un_start() { started = false; }
/**
* Sets the speed in revs per minute
*/
void TMC26XStepper::setSpeed(uint16_t whatSpeed) {
this->speed = whatSpeed;
this->step_delay = 60UL * sq(1000UL) / ((uint32_t)this->number_of_steps * (uint32_t)whatSpeed * (uint32_t)this->microsteps);
#ifdef TMC_DEBUG0 // crashes
SERIAL_ECHOPAIR("\nStep delay in micros: ", this->step_delay);
#endif
// Update the next step time
this->next_step_time = this->last_step_time + this->step_delay;
}
uint16_t TMC26XStepper::getSpeed(void) { return this->speed; }
/**
* Moves the motor steps_to_move steps.
* Negative indicates the reverse direction.
*/
char TMC26XStepper::step(int16_t steps_to_move) {
if (this->steps_left == 0) {
this->steps_left = ABS(steps_to_move); // how many steps to take
// determine direction based on whether steps_to_move is + or -:
if (steps_to_move > 0)
this->direction = 1;
else if (steps_to_move < 0)
this->direction = 0;
return 0;
}
return -1;
}
char TMC26XStepper::move(void) {
// decrement the number of steps, moving one step each time:
if (this->steps_left > 0) {
uint32_t time = micros();
// move only if the appropriate delay has passed:
// rem if (time >= this->next_step_time) {
if (ABS(time - this->last_step_time) > this->step_delay) {
// increment or decrement the step number,
// depending on direction:
if (this->direction == 1)
extDigitalWrite(step_pin, HIGH);
else {
extDigitalWrite(dir_pin, HIGH);
extDigitalWrite(step_pin, HIGH);
}
// get the timeStamp of when you stepped:
this->last_step_time = time;
this->next_step_time = time + this->step_delay;
// decrement the steps left:
steps_left--;
//disable the step & dir pins
extDigitalWrite(step_pin, LOW);
extDigitalWrite(dir_pin, LOW);
}
return -1;
}
return 0;
}
char TMC26XStepper::isMoving(void) { return this->steps_left > 0; }
uint16_t TMC26XStepper::getStepsLeft(void) { return this->steps_left; }
char TMC26XStepper::stop(void) {
//note to self if the motor is currently moving
char state = isMoving();
//stop the motor
this->steps_left = 0;
this->direction = 0;
//return if it was moving
return state;
}
void TMC26XStepper::setCurrent(uint16_t current) {
uint8_t current_scaling = 0;
//calculate the current scaling from the max current setting (in mA)
float mASetting = (float)current,
resistor_value = (float)this->resistor;
// remove vsense flag
this->driver_configuration_register_value &= ~(VSENSE);
// Derived from I = (cs + 1) / 32 * (Vsense / Rsense)
// leading to cs = 32 * R * I / V (with V = 0,31V oder 0,165V and I = 1000 * current)
// with Rsense = 0,15
// for vsense = 0,310V (VSENSE not set)
// or vsense = 0,165V (VSENSE set)
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
// Check if the current scalingis too low
if (current_scaling < 16) {
// Set the csense bit to get a use half the sense voltage (to support lower motor currents)
this->driver_configuration_register_value |= VSENSE;
// and recalculate the current setting
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
#ifdef TMC_DEBUG0 // crashes
SERIAL_ECHOPAIR("\nCS (Vsense=1): ",current_scaling);
} else {
SERIAL_ECHOPAIR("\nCS: ", current_scaling);
#endif
}
// do some sanity checks
NOMORE(current_scaling, 31);
// delete the old value
stallguard2_current_register_value &= ~(CURRENT_SCALING_PATTERN);
// set the new current scaling
stallguard2_current_register_value |= current_scaling;
// if started we directly send it to the motor
if (started) {
send262(driver_configuration_register_value);
send262(stallguard2_current_register_value);
}
}
uint16_t TMC26XStepper::getCurrent(void) {
// Calculate the current according to the datasheet to be on the safe side.
// This is not the fastest but the most accurate and illustrative way.
float result = (float)(stallguard2_current_register_value & CURRENT_SCALING_PATTERN),
resistor_value = (float)this->resistor,
voltage = (driver_configuration_register_value & VSENSE) ? 0.165 : 0.31;
result = (result + 1.0) / 32.0 * voltage / resistor_value * sq(1000.0);
return (uint16_t)result;
}
void TMC26XStepper::setStallGuardThreshold(char stallguard_threshold, char stallguard_filter_enabled) {
// We just have 5 bits
LIMIT(stallguard_threshold, -64, 63);
// Add trim down to 7 bits
stallguard_threshold &= 0x7F;
// Delete old StallGuard settings
stallguard2_current_register_value &= ~(STALL_GUARD_CONFIG_PATTERN);
if (stallguard_filter_enabled)
stallguard2_current_register_value |= STALL_GUARD_FILTER_ENABLED;
// Set the new StallGuard threshold
stallguard2_current_register_value |= (((uint32_t)stallguard_threshold << 8) & STALL_GUARD_CONFIG_PATTERN);
// If started we directly send it to the motor
if (started) send262(stallguard2_current_register_value);
}
char TMC26XStepper::getStallGuardThreshold(void) {
uint32_t stallguard_threshold = stallguard2_current_register_value & STALL_GUARD_VALUE_PATTERN;
//shift it down to bit 0
stallguard_threshold >>= 8;
//convert the value to an int16_t to correctly handle the negative numbers
char result = stallguard_threshold;
//check if it is negative and fill it up with leading 1 for proper negative number representation
//rem if (result & _BV(6)) {
if (TEST(result, 6)) result |= 0xC0;
return result;
}
char TMC26XStepper::getStallGuardFilter(void) {
if (stallguard2_current_register_value & STALL_GUARD_FILTER_ENABLED)
return -1;
return 0;
}
/**
* Set the number of microsteps per step.
* 0,2,4,8,16,32,64,128,256 is supported
* any value in between will be mapped to the next smaller value
* 0 and 1 set the motor in full step mode
*/
void TMC26XStepper::setMicrosteps(const int16_t in_steps) {
uint16_t setting_pattern;
if (in_steps >= 256) setting_pattern = 0;
else if (in_steps >= 128) setting_pattern = 1;
else if (in_steps >= 64) setting_pattern = 2;
else if (in_steps >= 32) setting_pattern = 3;
else if (in_steps >= 16) setting_pattern = 4;
else if (in_steps >= 8) setting_pattern = 5;
else if (in_steps >= 4) setting_pattern = 6;
else if (in_steps >= 2) setting_pattern = 7;
else if (in_steps <= 1) setting_pattern = 8; // 1 and 0 lead to full step
microsteps = _BV(8 - setting_pattern);
#ifdef TMC_DEBUG0 // crashes
SERIAL_ECHOPAIR("\n Microstepping: ", microsteps);
#endif
// Delete the old value
this->driver_control_register_value &= 0x000FFFF0UL;
// Set the new value
this->driver_control_register_value |= setting_pattern;
// If started we directly send it to the motor
if (started) send262(driver_control_register_value);
// Recalculate the stepping delay by simply setting the speed again
this->setSpeed(this->speed);
}
/**
* returns the effective number of microsteps at the moment
*/
int16_t TMC26XStepper::getMicrosteps(void) { return microsteps; }
/**
* 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.
* 2...15: off time setting
*
* 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
* 0: min. setting 3: max. setting
*
* fast_decay_time_setting: Fast decay time setting. With CHM=1, these bits control the portion of fast decay for each chopper cycle.
* 0: slow decay only
* 1...15: duration of fast decay phase
*
* sine_wave_offset: Sine wave offset. With CHM=1, these bits control the sine wave offset.
* A positive offset corrects for zero crossing error.
* -3..-1: negative offset 0: no offset 1...12: positive offset
*
* use_current_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.
* 1: enable comparator termination of fast decay cycle
* 0: end by time only
*/
void TMC26XStepper::setConstantOffTimeChopper(char constant_off_time, char blank_time, char fast_decay_time_setting, char sine_wave_offset, uint8_t use_current_comparator) {
// Perform some sanity checks
LIMIT(constant_off_time, 2, 15);
// Save the constant off time
this->constant_off_time = constant_off_time;
// Calculate the value acc to the clock cycles
const char blank_value = blank_time >= 54 ? 3 :
blank_time >= 36 ? 2 :
blank_time >= 24 ? 1 : 0;
LIMIT(fast_decay_time_setting, 0, 15);
LIMIT(sine_wave_offset, -3, 12);
// Shift the sine_wave_offset
sine_wave_offset += 3;
// Calculate the register setting
// First of all delete all the values for this
chopper_config_register &= ~(_BV(12) | BLANK_TIMING_PATTERN | HYSTERESIS_DECREMENT_PATTERN | HYSTERESIS_LOW_VALUE_PATTERN | HYSTERESIS_START_VALUE_PATTERN | T_OFF_TIMING_PATERN);
// Set the constant off pattern
chopper_config_register |= CHOPPER_MODE_T_OFF_FAST_DECAY;
// Set the blank timing value
chopper_config_register |= ((uint32_t)blank_value) << BLANK_TIMING_SHIFT;
// Setting the constant off time
chopper_config_register |= constant_off_time;
// Set the fast decay time
// Set msb
chopper_config_register |= (((uint32_t)(fast_decay_time_setting & 0x8)) << HYSTERESIS_DECREMENT_SHIFT);
// Other bits
chopper_config_register |= (((uint32_t)(fast_decay_time_setting & 0x7)) << HYSTERESIS_START_VALUE_SHIFT);
// Set the sine wave offset
chopper_config_register |= (uint32_t)sine_wave_offset << HYSTERESIS_LOW_SHIFT;
// Using the current comparator?
if (!use_current_comparator)
chopper_config_register |= _BV(12);
// If started we directly send it to the motor
if (started) {
// rem send262(driver_control_register_value);
send262(chopper_config_register);
}
}
/**
* 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.
* 2...15: off time setting
*
* 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
* 0: min. setting 3: max. setting
*
* hysteresis_start: Hysteresis start setting. Please remark, that this value is an offset to the hysteresis end value HEND.
* 1...8
*
* hysteresis_end: Hysteresis end setting. Sets the hysteresis end value after a number of decrements. Decrement interval time is controlled by HDEC.
* The sum HSTRT+HEND must be <16. At a current setting CS of max. 30 (amplitude reduced to 240), the sum is not limited.
* -3..-1: negative HEND 0: zero HEND 1...12: positive HEND
*
* 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: very slow decrement
*/
void TMC26XStepper::setSpreadCycleChopper(char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement) {
// Perform some sanity checks
LIMIT(constant_off_time, 2, 15);
// Save the constant off time
this->constant_off_time = constant_off_time;
// Calculate the value acc to the clock cycles
const char blank_value = blank_time >= 54 ? 3 :
blank_time >= 36 ? 2 :
blank_time >= 24 ? 1 : 0;
LIMIT(hysteresis_start, 1, 8);
hysteresis_start--;
LIMIT(hysteresis_start, -3, 12);
// Shift the hysteresis_end
hysteresis_end += 3;
LIMIT(hysteresis_decrement, 0, 3);
//first of all delete all the values for this
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);
//set the blank timing value
chopper_config_register |= ((uint32_t)blank_value) << BLANK_TIMING_SHIFT;
//setting the constant off time
chopper_config_register |= constant_off_time;
//set the hysteresis_start
chopper_config_register |= ((uint32_t)hysteresis_start) << HYSTERESIS_START_VALUE_SHIFT;
//set the hysteresis end
chopper_config_register |= ((uint32_t)hysteresis_end) << HYSTERESIS_LOW_SHIFT;
//set the hystereis decrement
chopper_config_register |= ((uint32_t)blank_value) << BLANK_TIMING_SHIFT;
//if started we directly send it to the motor
if (started) {
//rem send262(driver_control_register_value);
send262(chopper_config_register);
}
}
/**
* In a constant off time chopper scheme both coil choppers run freely, i.e. are not synchronized.
* 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.
* 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
* few microstep positions within each quarter wave. This effect normally is not audible when compared to mechanical noise generated by ball bearings, etc.
* Further factors which can cause a similar effect are a poor layout of sense resistor GND connection.
* Hint: A common factor, which can cause motor noise, is a bad PCB layout causing coupling of both sense resistor voltages
* (please refer to sense resistor layout hint in chapter 8.1).
* In order to minimize the effect of a beat between both chopper frequencies, an internal random generator is provided.
* It modulates the slow decay time setting when switched on by the RNDTF bit. The RNDTF feature further spreads the chopper spectrum,
* reducing electromagnetic emission on single frequencies.
*/
void TMC26XStepper::setRandomOffTime(char value) {
if (value)
chopper_config_register |= RANDOM_TOFF_TIME;
else
chopper_config_register &= ~(RANDOM_TOFF_TIME);
//if started we directly send it to the motor
if (started) {
//rem send262(driver_control_register_value);
send262(chopper_config_register);
}
}
void TMC26XStepper::setCoolStepConfiguration(
uint16_t lower_SG_threshold,
uint16_t SG_hysteresis,
uint8_t current_decrement_step_size,
uint8_t current_increment_step_size,
uint8_t lower_current_limit
) {
// Sanitize the input values
NOMORE(lower_SG_threshold, 480);
// Divide by 32
lower_SG_threshold >>= 5;
NOMORE(SG_hysteresis, 480);
// Divide by 32
SG_hysteresis >>= 5;
NOMORE(current_decrement_step_size, 3);
NOMORE(current_increment_step_size, 3);
NOMORE(lower_current_limit, 1);
// Store the lower level in order to enable/disable the cool step
this->cool_step_lower_threshold=lower_SG_threshold;
// If cool step is not enabled we delete the lower value to keep it disabled
if (!this->cool_step_enabled) lower_SG_threshold = 0;
// The good news is that we can start with a complete new cool step register value
// And simply set the values in the register
cool_step_register_value = ((uint32_t)lower_SG_threshold)
| (((uint32_t)SG_hysteresis) << 8)
| (((uint32_t)current_decrement_step_size) << 5)
| (((uint32_t)current_increment_step_size) << 13)
| (((uint32_t)lower_current_limit) << 15)
| COOL_STEP_REGISTER; // Register signature
if (started) send262(cool_step_register_value);
}
void TMC26XStepper::setCoolStepEnabled(boolean enabled) {
// Simply delete the lower limit to disable the cool step
cool_step_register_value &= ~SE_MIN_PATTERN;
// And set it to the proper value if cool step is to be enabled
if (enabled)
cool_step_register_value |= this->cool_step_lower_threshold;
// And save the enabled status
this->cool_step_enabled = enabled;
// Save the register value
if (started) send262(cool_step_register_value);
}
boolean TMC26XStepper::isCoolStepEnabled(void) { return this->cool_step_enabled; }
uint16_t TMC26XStepper::getCoolStepLowerSgThreshold() {
// We return our internally stored value - in order to provide the correct setting even if cool step is not enabled
return this->cool_step_lower_threshold<<5;
}
uint16_t TMC26XStepper::getCoolStepUpperSgThreshold() {
return uint8_t((cool_step_register_value & SE_MAX_PATTERN) >> 8) << 5;
}
uint8_t TMC26XStepper::getCoolStepCurrentIncrementSize() {
return uint8_t((cool_step_register_value & CURRENT_DOWN_STEP_SPEED_PATTERN) >> 13);
}
uint8_t TMC26XStepper::getCoolStepNumberOfSGReadings() {
return uint8_t((cool_step_register_value & SE_CURRENT_STEP_WIDTH_PATTERN) >> 5);
}
uint8_t TMC26XStepper::getCoolStepLowerCurrentLimit() {
return uint8_t((cool_step_register_value & MINIMUM_CURRENT_FOURTH) >> 15);
}
void TMC26XStepper::setEnabled(boolean enabled) {
//delete the t_off in the chopper config to get sure
chopper_config_register &= ~(T_OFF_PATTERN);
if (enabled) {
//and set the t_off time
chopper_config_register |= this->constant_off_time;
}
//if not enabled we don't have to do anything since we already delete t_off from the register
if (started) send262(chopper_config_register);
}
boolean TMC26XStepper::isEnabled() { return !!(chopper_config_register & T_OFF_PATTERN); }
/**
* reads a value from the TMC26X status register. The value is not obtained directly but can then
* be read by the various status routines.
*
*/
void TMC26XStepper::readStatus(char read_value) {
uint32_t old_driver_configuration_register_value = driver_configuration_register_value;
//reset the readout configuration
driver_configuration_register_value &= ~(READ_SELECTION_PATTERN);
//this now equals TMC26X_READOUT_POSITION - so we just have to check the other two options
if (read_value == TMC26X_READOUT_STALLGUARD)
driver_configuration_register_value |= READ_STALL_GUARD_READING;
else if (read_value == TMC26X_READOUT_CURRENT)
driver_configuration_register_value |= READ_STALL_GUARD_AND_COOL_STEP;
//all other cases are ignored to prevent funny values
//check if the readout is configured for the value we are interested in
if (driver_configuration_register_value != old_driver_configuration_register_value) {
//because then we need to write the value twice - one time for configuring, second time to get the value, see below
send262(driver_configuration_register_value);
}
//write the configuration to get the last status
send262(driver_configuration_register_value);
}
int16_t TMC26XStepper::getMotorPosition(void) {
//we read it out even if we are not started yet - perhaps it is useful information for somebody
readStatus(TMC26X_READOUT_POSITION);
return getReadoutValue();
}
//reads the StallGuard setting from last status
//returns -1 if StallGuard information is not present
int16_t TMC26XStepper::getCurrentStallGuardReading(void) {
//if we don't yet started there cannot be a StallGuard value
if (!started) return -1;
//not time optimal, but solution optiomal:
//first read out the StallGuard value
readStatus(TMC26X_READOUT_STALLGUARD);
return getReadoutValue();
}
uint8_t TMC26XStepper::getCurrentCSReading(void) {
//if we don't yet started there cannot be a StallGuard value
if (!started) return 0;
//not time optimal, but solution optiomal:
//first read out the StallGuard value
readStatus(TMC26X_READOUT_CURRENT);
return (getReadoutValue() & 0x1F);
}
uint16_t TMC26XStepper::getCurrentCurrent(void) {
float result = (float)getCurrentCSReading(),
resistor_value = (float)this->resistor,
voltage = (driver_configuration_register_value & VSENSE)? 0.165 : 0.31;
result = (result + 1.0) / 32.0 * voltage / resistor_value * sq(1000.0);
return (uint16_t)result;
}
/**
* Return true if the StallGuard threshold has been reached
*/
boolean TMC26XStepper::isStallGuardOverThreshold(void) {
if (!this->started) return false;
return (driver_status_result & STATUS_STALL_GUARD_STATUS);
}
/**
* returns if there is any over temperature condition:
* OVER_TEMPERATURE_PREWARING if pre warning level has been reached
* OVER_TEMPERATURE_SHUTDOWN if the temperature is so hot that the driver is shut down
* Any of those levels are not too good.
*/
char TMC26XStepper::getOverTemperature(void) {
if (!this->started) return 0;
if (driver_status_result & STATUS_OVER_TEMPERATURE_SHUTDOWN)
return TMC26X_OVERTEMPERATURE_SHUTDOWN;
if (driver_status_result & STATUS_OVER_TEMPERATURE_WARNING)
return TMC26X_OVERTEMPERATURE_PREWARING;
return 0;
}
// Is motor channel A shorted to ground
boolean TMC26XStepper::isShortToGroundA(void) {
if (!this->started) return false;
return (driver_status_result & STATUS_SHORT_TO_GROUND_A);
}
// Is motor channel B shorted to ground
boolean TMC26XStepper::isShortToGroundB(void) {
if (!this->started) return false;
return (driver_status_result & STATUS_SHORT_TO_GROUND_B);
}
// Is motor channel A connected
boolean TMC26XStepper::isOpenLoadA(void) {
if (!this->started) return false;
return (driver_status_result & STATUS_OPEN_LOAD_A);
}
// Is motor channel B connected
boolean TMC26XStepper::isOpenLoadB(void) {
if (!this->started) return false;
return (driver_status_result & STATUS_OPEN_LOAD_B);
}
// Is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
boolean TMC26XStepper::isStandStill(void) {
if (!this->started) return false;
return (driver_status_result & STATUS_STAND_STILL);
}
//is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
boolean TMC26XStepper::isStallGuardReached(void) {
if (!this->started) return false;
return (driver_status_result & STATUS_STALL_GUARD_STATUS);
}
//reads the StallGuard setting from last status
//returns -1 if StallGuard information is not present
int16_t TMC26XStepper::getReadoutValue(void) {
return (int)(driver_status_result >> 10);
}
int16_t TMC26XStepper::getResistor() { return this->resistor; }
boolean TMC26XStepper::isCurrentScalingHalfed() {
return !!(this->driver_configuration_register_value & VSENSE);
}
/**
* version() returns the version of the library:
*/
int16_t TMC26XStepper::version(void) { return 1; }
void TMC26XStepper::debugLastStatus() {
#ifdef TMC_DEBUG1
if (this->started) {
if (this->getOverTemperature()&TMC26X_OVERTEMPERATURE_PREWARING)
SERIAL_ECHOLNPGM("\n WARNING: Overtemperature Prewarning!");
else if (this->getOverTemperature()&TMC26X_OVERTEMPERATURE_SHUTDOWN)
SERIAL_ECHOLNPGM("\n ERROR: Overtemperature Shutdown!");
if (this->isShortToGroundA())
SERIAL_ECHOLNPGM("\n ERROR: SHORT to ground on channel A!");
if (this->isShortToGroundB())
SERIAL_ECHOLNPGM("\n ERROR: SHORT to ground on channel B!");
if (this->isOpenLoadA())
SERIAL_ECHOLNPGM("\n ERROR: Channel A seems to be unconnected!");
if (this->isOpenLoadB())
SERIAL_ECHOLNPGM("\n ERROR: Channel B seems to be unconnected!");
if (this->isStallGuardReached())
SERIAL_ECHOLNPGM("\n INFO: Stall Guard level reached!");
if (this->isStandStill())
SERIAL_ECHOLNPGM("\n INFO: Motor is standing still.");
uint32_t readout_config = driver_configuration_register_value & READ_SELECTION_PATTERN;
const int16_t value = getReadoutValue();
if (readout_config == READ_MICROSTEP_POSTION) {
SERIAL_ECHOPAIR("\n Microstep position phase A: ", value);
}
else if (readout_config == READ_STALL_GUARD_READING) {
SERIAL_ECHOPAIR("\n Stall Guard value:", value);
}
else if (readout_config == READ_STALL_GUARD_AND_COOL_STEP) {
int16_t stallGuard = value & 0xF, current = value & 0x1F0;
SERIAL_ECHOPAIR("\n Approx Stall Guard: ", stallGuard);
SERIAL_ECHOPAIR("\n Current level", current);
}
}
#endif
}
/**
* send register settings to the stepper driver via SPI
* returns the current status
*/
inline void TMC26XStepper::send262(uint32_t datagram) {
uint32_t i_datagram;
//preserver the previous spi mode
//uint8_t oldMode = SPCR & SPI_MODE_MASK;
//if the mode is not correct set it to mode 3
//if (oldMode != SPI_MODE3) {
// SPI.setDataMode(SPI_MODE3);
//}
//select the TMC driver
extDigitalWrite(cs_pin, LOW);
//ensure that only valid bist are set (0-19)
//datagram &=REGISTER_BIT_PATTERN;
#ifdef TMC_DEBUG1
//SERIAL_PRINTF("Sending ");
//SERIAL_PRINTF("Sending ", datagram,HEX);
//SERIAL_ECHOPAIR("\n\nSending \n", print_hex_long(datagram));
SERIAL_PRINTF("\n\nSending %x", datagram);
#endif
//write/read the values
i_datagram = STEPPER_SPI.transfer((datagram >> 16) & 0xFF);
i_datagram <<= 8;
i_datagram |= STEPPER_SPI.transfer((datagram >> 8) & 0xFF);
i_datagram <<= 8;
i_datagram |= STEPPER_SPI.transfer((datagram) & 0xFF);
i_datagram >>= 4;
#ifdef TMC_DEBUG1
//SERIAL_PRINTF("Received ");
//SERIAL_PRINTF("Received ", i_datagram,HEX);
//SERIAL_ECHOPAIR("\n\nReceived \n", i_datagram);
SERIAL_PRINTF("\n\nReceived %x", i_datagram);
debugLastStatus();
#endif
//deselect the TMC chip
extDigitalWrite(cs_pin, HIGH);
//restore the previous SPI mode if neccessary
//if the mode is not correct set it to mode 3
//if (oldMode != SPI_MODE3) {
// SPI.setDataMode(oldMode);
//}
//store the datagram as status result
driver_status_result = i_datagram;
}
#endif // STM32GENERIC && STM32F7

View File

@@ -0,0 +1,594 @@
/**
* TMC26XStepper.h - - TMC26X Stepper library for Wiring/Arduino
*
* based on the stepper library by Tom Igoe, et. al.
*
* Copyright (c) 2011, Interactive Matter, Marcus Nowotny
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#pragma once
#include <stdint.h>
//! return value for TMC26XStepper.getOverTemperature() if there is a overtemperature situation in the TMC chip
/*!
* This warning indicates that the TMC chip is too warm.
* It is still working but some parameters may be inferior.
* You should do something against it.
*/
#define TMC26X_OVERTEMPERATURE_PREWARING 1
//! return value for TMC26XStepper.getOverTemperature() if there is a overtemperature shutdown in the TMC chip
/*!
* This warning indicates that the TMC chip is too warm to operate and has shut down to prevent damage.
* It will stop working until it cools down again.
* If you encouter this situation you must do something against it. Like reducing the current or improving the PCB layout
* and/or heat management.
*/
#define TMC26X_OVERTEMPERATURE_SHUTDOWN 2
//which values can be read out
/*!
* Selects to readout the microstep position from the motor.
*\sa readStatus()
*/
#define TMC26X_READOUT_POSITION 0
/*!
* Selects to read out the StallGuard value of the motor.
*\sa readStatus()
*/
#define TMC26X_READOUT_STALLGUARD 1
/*!
* Selects to read out the current current setting (acc. to CoolStep) and the upper bits of the StallGuard value from the motor.
*\sa readStatus(), setCurrent()
*/
#define TMC26X_READOUT_CURRENT 3
/*!
* Define to set the minimum current for CoolStep operation to 1/2 of the selected CS minium.
*\sa setCoolStepConfiguration()
*/
#define COOL_STEP_HALF_CS_LIMIT 0
/*!
* Define to set the minimum current for CoolStep operation to 1/4 of the selected CS minium.
*\sa setCoolStepConfiguration()
*/
#define COOL_STEP_QUARTDER_CS_LIMIT 1
/*!
* \class TMC26XStepper
* \brief Class representing a TMC26X stepper driver
*
* To use one of these drivers in your code create an object of its class:
* \code
* TMC26XStepper tmc_stepper = TMC26XStepper(200,1,2,3,500);
* \endcode
* see TMC26XStepper(int16_t number_of_steps, int16_t cs_pin, int16_t dir_pin, int16_t step_pin, uint16_t rms_current)
*
* Keep in mind that you need to start the driver with start() in order to configure the TMC26X.
*
* The most important function is move(). It checks if the motor requires a step. It's important to call move() as
* often as possible in loop(). I suggest using a very fast loop routine and always call move() at the beginning or end.
*
* To move you must set a movement speed with setSpeed(). The speed is a positive value, setting the RPM.
*
* To really move the motor you have to call step() to tell the driver to move the motor the given number
* of steps in the given direction. Positive values move the motor in one direction, negative values in the other.
*
* You can check with isMoving() if the motor is still moving or stop it abruptly with stop().
*/
class TMC26XStepper {
public:
/*!
* \brief Create a new representation of a stepper motor connected to a TMC26X stepper driver
*
* Main constructor. If in doubt use this. All parameters must be provided as described below.
*
* \param number_of_steps Number of steps the motor has per rotation.
* \param cs_pin Arduino pin connected to the Client Select Pin (!CS) of the TMC26X for SPI.
* \param dir_pin Arduino pin connected to the DIR input of the TMC26X.
* \param step_pin Arduino pin connected to the STEP pin of the TMC26X.
* \param rms_current Maximum current to provide to the motor in mA (!). A value of 200 will send up to 200mA to the motor.
* \param resistor Current sense resistor in milli-Ohm, defaults to 0.15 Ohm (or 150 milli-Ohm) as in the TMC260 Arduino Shield.
*
* You must also call TMC26XStepper.start() to configure the stepper driver for use.
*
* By default the Constant Off Time chopper is used. See TMC26XStepper.setConstantOffTimeChopper() for details.
* This should work on most motors (YMMV). You may want to configure and use the Spread Cycle Chopper. See setSpreadCycleChopper().
*
* By default a microstepping of 1/32 is used to provide a smooth motor run while still giving a good progression per step.
* Change stepping by sending setMicrosteps() a different value.
* \sa start(), setMicrosteps()
*/
TMC26XStepper(const int16_t in_steps, int16_t cs_pin, int16_t dir_pin, int16_t step_pin, uint16_t current, uint16_t resistor=100); //resistor=150
/*!
* \brief Configure and start the TMC26X stepper driver. Before this is called the stepper driver is nonfunctional.
*
* Configure the TMC26X stepper driver for the given values via SPI.
* Most member functions are non-functional if the driver has not been started,
* therefore it is best to call this in setup().
*/
void start();
/*!
* \brief Reset the stepper in unconfigured mode.
*
* Allows start to be called again. It doesn't change the internal stepper
* configuration or the desired configuration. It just marks the stepper as
* not-yet-started. The stepper doesn't need to be reconfigured before
* starting again, and is not reset to any factory settings.
* It must be reset intentionally.
* (Hint: Normally you do not need this function)
*/
void un_start();
/*!
* \brief Set the rotation speed in RPM.
* \param whatSpeed the desired speed in RPM.
*/
void setSpeed(uint16_t whatSpeed);
/*!
* \brief Report the currently selected speed in RPM.
* \sa setSpeed()
*/
uint16_t getSpeed(void);
/*!
* \brief Set the number of microsteps in 2^i values (rounded) up to 256
*
* This method sets the number of microsteps per step in 2^i interval.
* It accepts 1, 2, 4, 16, 32, 64, 128 or 256 as valid microsteps.
* Other values will be rounded down to the next smaller value (e.g., 3 gives a microstepping of 2).
* You can always check the current microstepping with getMicrosteps().
*/
void setMicrosteps(const int16_t in_steps);
/*!
* \brief Return the effective current number of microsteps selected.
*
* Always returns the effective number of microsteps.
* This may be different from the micro-steps set in setMicrosteps() since it is rounded to 2^i.
*
* \sa setMicrosteps()
*/
int16_t getMicrosteps(void);
/*!
* \brief Initiate a movement with the given number of steps. Positive values move in one direction, negative in the other.
*
* \param number_of_steps The number of steps to move the motor.
* \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.
*
* If the previous movement is incomplete the function returns -1 and doesn't change the steps to move the motor.
* If the motor does not move it returns 0.
*
* The movement direction is determined by the sign of the steps parameter. The motor direction in machine space
* cannot be determined, as it depends on the construction of the motor and how it functions in the drive system.
*
* For safety, verify with isMoving() or even use stop() to stop the motor before giving it new step directions.
* \sa isMoving(), getStepsLeft(), stop()
*/
char step(int16_t number_of_steps);
/*!
* \brief Central movement method. Must be called as often as possible in the loop function and is very fast.
*
* Check if the motor still has to move and whether the wait-to-step interval has expired, and manages the
* number of steps remaining to fulfill the current move command.
*
* This function is implemented to be as fast as possible, so call it as often as possible in your loop.
* It should be invoked with as frequently and with as much regularity as possible.
*
* This can be called even when the motor is known not to be moving. It will simply return.
*
* The frequency with which this function is called determines the top stepping speed of the motor.
* It is recommended to call this using a hardware timer to ensure regular invocation.
* \sa step()
*/
char move(void);
/*!
* \brief Check whether the last movement command is done.
* \return 0 if the motor stops, -1 if the motor is moving.
*
* Used to determine if the motor is ready for new movements.
*\sa step(), move()
*/
char isMoving(void);
/*!
* \brief Get the number of steps left in the current movement.
* \return The number of steps left in the movement. Always positive.
*/
uint16_t getStepsLeft(void);
/*!
* \brief Stop the motor immediately.
* \return -1 if the motor was moving and is really stoped or 0 if it was not moving at all.
*
* This method directly and abruptly stops the motor and may be used as an emergency stop.
*/
char stop(void);
/*!
* \brief Set and configure the classical Constant Off Timer Chopper
* \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)
* \param blank_time Comparator blank time. This duration needs to safely cover the duration of the switching event and 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
* \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
* \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
* \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).
*
* The classic constant off time chopper uses a fixed portion of fast decay following each on phase.
* While the duration of the on time is determined by the chopper comparator, the fast decay time needs
* to be set by the user in a way, that the current decay is enough for the driver to be able to follow
* the falling slope of the sine wave, and on the other hand it should not be too long, in order to minimize
* motor current ripple and power dissipation. This best can be tuned using an oscilloscope or
* trying out motor smoothness at different velocities. A good starting value is a fast decay time setting
* similar to the slow decay time setting.
* After tuning of the fast decay time, the offset should be determined, in order to have a smooth zero transition.
* This is necessary, because the fast decay phase leads to the absolute value of the motor current being lower
* than the target current (see figure 17). If the zero offset is too low, the motor stands still for a short
* moment during current zero crossing, if it is set too high, it makes a larger microstep.
* Typically, a positive offset setting is required for optimum operation.
*
* \sa setSpreadCycleChoper() for other alternatives.
* \sa setRandomOffTime() for spreading the noise over a wider spectrum
*/
void setConstantOffTimeChopper(char constant_off_time, char blank_time, char fast_decay_time_setting, char sine_wave_offset, uint8_t use_current_comparator);
/*!
* \brief Sets and configures with spread cycle chopper.
* \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)
* \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
* \param hysteresis_start Hysteresis start setting. Please remark, that this value is an offset to the hysteresis end value. 1 … 8
* \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.
* \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).
*
* The spreadCycle chopper scheme (pat.fil.) is a precise and simple to use chopper principle, which automatically determines
* the optimum fast decay portion for the motor. Anyhow, a number of settings can be made in order to optimally fit the driver
* to the motor.
* Each chopper cycle is comprised of an on-phase, a slow decay phase, a fast decay phase and a second slow decay phase.
* The slow decay phases limit the maximum chopper frequency and are important for low motor and driver power dissipation.
* The hysteresis start setting limits the chopper frequency by forcing the driver to introduce a minimum amount of
* current ripple into the motor coils. The motor inductivity determines the ability to follow a changing motor current.
* The duration of the on- and fast decay phase needs to cover at least the blank time, because the current comparator is
* disabled during this time.
*
* \sa setRandomOffTime() for spreading the noise over a wider spectrum
*/
void setSpreadCycleChopper(char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement);
/*!
* \brief Use random off time for noise reduction (0 for off, -1 for on).
* \param value 0 for off, -1 for on
*
* In a constant off time chopper scheme both coil choppers run freely, i.e. are not synchronized.
* 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. 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 few microstep positions within
* each quarter wave.
* This effect normally is not audible when compared to mechanical noise generated by ball bearings,
* etc. Further factors which can cause a similar effect are a poor layout of sense resistor GND connection.
* In order to minimize the effect of a beat between both chopper frequencies, an internal random generator is provided.
* It modulates the slow decay time setting when switched on. The random off time feature further spreads the chopper spectrum,
* reducing electromagnetic emission on single frequencies.
*/
void setRandomOffTime(char value);
/*!
* \brief set the maximum motor current in mA (1000 is 1 Amp)
* 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
* by employing CoolStep.
* \param current the maximum motor current in mA
* \sa getCurrent(), getCurrentCurrent()
*/
void setCurrent(uint16_t current);
/*!
* \brief readout the motor maximum current in mA (1000 is an Amp)
* This is the maximum current. to get the current current - which may be affected by CoolStep us getCurrentCurrent()
* \return the maximum motor current in milli amps
* \sa getCurrentCurrent()
*/
uint16_t getCurrent(void);
/*!
* \brief set the StallGuard threshold in order to get sensible StallGuard readings.
* \param stallguard_threshold -64 … 63 the StallGuard threshold
* \param stallguard_filter_enabled 0 if the filter is disabled, -1 if it is enabled
*
* The StallGuard threshold is used to optimize the StallGuard reading to sensible values. It should be at 0 at
* the maximum allowable load on the otor (but not before). = is a good starting point (and the default)
* If you get Stall Gaurd readings of 0 without any load or with too little laod increase the value.
* If you get readings of 1023 even with load decrease the setting.
*
* If you switch on the filter the StallGuard reading is only updated each 4th full step to reduce the noise in the
* reading.
*
* \sa getCurrentStallGuardReading() to read out the current value.
*/
void setStallGuardThreshold(char stallguard_threshold, char stallguard_filter_enabled);
/*!
* \brief reads out the StallGuard threshold
* \return a number between -64 and 63.
*/
char getStallGuardThreshold(void);
/*!
* \brief returns the current setting of the StallGuard filter
* \return 0 if not set, -1 if set
*/
char getStallGuardFilter(void);
/*!
* \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.
* \param lower_SG_threshold Sets the lower threshold for stallGuard2TM reading. Below this value, the motor current becomes increased. Allowed values are 0...480
* \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
* \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
* \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
* \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
* The CoolStep smart energy operation automatically adjust the current sent into the motor according to the current load,
* read out by the StallGuard in order to provide the optimum torque with the minimal current consumption.
* You configure the CoolStep current regulator by defining upper and lower bounds of StallGuard readouts. If the readout is above the
* limit the current gets increased, below the limit the current gets decreased.
* 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
* StallGuard readings neccessary above or below the limit to get a more stable current adjustement.
* The current adjustement itself is configured by the number of steps the current gests in- or decreased and the absolut minimum current
* (1/2 or 1/4th otf the configured current).
* \sa COOL_STEP_HALF_CS_LIMIT, COOL_STEP_QUARTER_CS_LIMIT
*/
void setCoolStepConfiguration(uint16_t lower_SG_threshold, uint16_t SG_hysteresis, uint8_t current_decrement_step_size,
uint8_t current_increment_step_size, uint8_t lower_current_limit);
/*!
* \brief enables or disables the CoolStep smart energy operation feature. It must be configured before enabling it.
* \param enabled true if CoolStep should be enabled, false if not.
* \sa setCoolStepConfiguration()
*/
void setCoolStepEnabled(boolean enabled);
/*!
* \brief check if the CoolStep feature is enabled
* \sa setCoolStepEnabled()
*/
boolean isCoolStepEnabled();
/*!
* \brief returns the lower StallGuard threshold for the CoolStep operation
* \sa setCoolStepConfiguration()
*/
uint16_t getCoolStepLowerSgThreshold();
/*!
* \brief returns the upper StallGuard threshold for the CoolStep operation
* \sa setCoolStepConfiguration()
*/
uint16_t getCoolStepUpperSgThreshold();
/*!
* \brief returns the number of StallGuard readings befor CoolStep adjusts the motor current.
* \sa setCoolStepConfiguration()
*/
uint8_t getCoolStepNumberOfSGReadings();
/*!
* \brief returns the increment steps for the current for the CoolStep operation
* \sa setCoolStepConfiguration()
*/
uint8_t getCoolStepCurrentIncrementSize();
/*!
* \brief returns the absolut minium current for the CoolStep operation
* \sa setCoolStepConfiguration()
* \sa COOL_STEP_HALF_CS_LIMIT, COOL_STEP_QUARTER_CS_LIMIT
*/
uint8_t getCoolStepLowerCurrentLimit();
/*!
* \brief Get the current microstep position for phase A
* \return The current microstep position for phase A 0…255
*
* Keep in mind that this routine reads and writes a value via SPI - so this may take a bit time.
*/
int16_t getMotorPosition(void);
/*!
* \brief Reads the current StallGuard value.
* \return The current StallGuard value, lesser values indicate higher load, 0 means stall detected.
* Keep in mind that this routine reads and writes a value via SPI - so this may take a bit time.
* \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
*/
int16_t getCurrentStallGuardReading(void);
/*!
* \brief Reads the current current setting value as fraction of the maximum current
* Returns values between 0 and 31, representing 1/32 to 32/32 (=1)
* \sa setCoolStepConfiguration()
*/
uint8_t getCurrentCSReading(void);
/*!
*\brief a convenience method to determine if the current scaling uses 0.31V or 0.165V as reference.
*\return false if 0.13V is the reference voltage, true if 0.165V is used.
*/
boolean isCurrentScalingHalfed();
/*!
* \brief Reads the current current setting value and recalculates the absolute current in mA (1A would be 1000).
* This method calculates the currently used current setting (either by setting or by CoolStep) and reconstructs
* the current in mA by usinge the VSENSE and resistor value. This method uses floating point math - so it
* may not be the fastest.
* \sa getCurrentCSReading(), getResistor(), isCurrentScalingHalfed(), getCurrent()
*/
uint16_t getCurrentCurrent(void);
/*!
* \brief checks if there is a StallGuard warning in the last status
* \return 0 if there was no warning, -1 if there was some warning.
* Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
* You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
*
* \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
*/
boolean isStallGuardOverThreshold(void);
/*!
* \brief Return over temperature status of the last status readout
* 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.
* Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
* You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
*/
char getOverTemperature(void);
/*!
* \brief Is motor channel A shorted to ground detected in the last status readout.
* \return true is yes, false if not.
* Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
* You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
*/
boolean isShortToGroundA(void);
/*!
* \brief Is motor channel B shorted to ground detected in the last status readout.
* \return true is yes, false if not.
* Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
* You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
*/
boolean isShortToGroundB(void);
/*!
* \brief iIs motor channel A connected according to the last statu readout.
* \return true is yes, false if not.
* Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
* You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
*/
boolean isOpenLoadA(void);
/*!
* \brief iIs motor channel A connected according to the last statu readout.
* \return true is yes, false if not.
* Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
* You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
*/
boolean isOpenLoadB(void);
/*!
* \brief Is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
* \return true is yes, false if not.
* Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
* You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
*/
boolean isStandStill(void);
/*!
* \brief checks if there is a StallGuard warning in the last status
* \return 0 if there was no warning, -1 if there was some warning.
* Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
* You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
*
* \sa isStallGuardOverThreshold()
* TODO why?
*
* \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
*/
boolean isStallGuardReached(void);
/*!
*\brief enables or disables the motor driver bridges. If disabled the motor can run freely. If enabled not.
*\param enabled a boolean value true if the motor should be enabled, false otherwise.
*/
void setEnabled(boolean enabled);
/*!
*\brief checks if the output bridges are enabled. If the bridges are not enabled the motor can run freely
*\return true if the bridges and by that the motor driver are enabled, false if not.
*\sa setEnabled()
*/
boolean isEnabled();
/*!
* \brief Manually read out the status register
* This function sends a byte to the motor driver in order to get the current readout. The parameter read_value
* seletcs which value will get returned. If the read_vlaue changes in respect to the previous readout this method
* automatically send two bytes to the motor: one to set the redout and one to get the actual readout. So this method
* may take time to send and read one or two bits - depending on the previous readout.
* \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
* \sa TMC26X_READOUT_POSITION, TMC_262_READOUT_STALLGUARD, TMC_262_READOUT_CURRENT
*/
void readStatus(char read_value);
/*!
* \brief Returns the current sense resistor value in milliohm.
* The default value of ,15 Ohm will return 150.
*/
int16_t getResistor();
/*!
* \brief Prints out all the information that can be found in the last status read out - it does not force a status readout.
* The result is printed via Serial
*/
void debugLastStatus(void);
/*!
* \brief library version
* \return the version number as int.
*/
int16_t version(void);
private:
uint16_t steps_left; // The steps the motor has to do to complete the movement
int16_t direction; // Direction of rotation
uint32_t step_delay; // Delay between steps, in ms, based on speed
int16_t number_of_steps; // Total number of steps this motor can take
uint16_t speed; // Store the current speed in order to change the speed after changing microstepping
uint16_t resistor; // Current sense resitor value in milliohm
uint32_t last_step_time, // Timestamp (ms) of the last step
next_step_time; // Timestamp (ms) of the next step
// Driver control register copies to easily set & modify the registers
uint32_t driver_control_register_value,
chopper_config_register,
cool_step_register_value,
stallguard2_current_register_value,
driver_configuration_register_value,
driver_status_result; // The driver status result
// Helper routione to get the top 10 bit of the readout
inline int16_t getReadoutValue();
// The pins for the stepper driver
uint8_t cs_pin, step_pin, dir_pin;
// Status values
boolean started; // If the stepper has been started yet
int16_t microsteps; // The current number of micro steps
char constant_off_time; // We need to remember this value in order to enable and disable the motor
uint8_t cool_step_lower_threshold; // we need to remember the threshold to enable and disable the CoolStep feature
boolean cool_step_enabled; // We need to remember this to configure the coolstep if it si enabled
// SPI sender
inline void send262(uint32_t datagram);
};