Arduino_Core_STM32 icon indicating copy to clipboard operation
Arduino_Core_STM32 copied to clipboard

STM32F103 - 'TIM4' was not declared in this scope

Open Contomo opened this issue 3 years ago • 4 comments

Hello, none of the F103 boards seem to compile with Timer4 in the attatched code, PB6 maps to TIM4 channel 1, the code as posted compiles, but crashes the microcontroller, changing the

HardwareTimer *TimerSteppers = new HardwareTimer(Instance); to: HardwareTimer *TimerSteppers = new HardwareTimer(TIM4); it doesnt compile anymore as it cant find TIM4.

The code posted was tested on an STM32F411, compiled fine, uploaded fine, and ran well (until i accidentally killed the chip)

i tried updating to the latest versioon, using arduino 1.8.13 (Timer 5 and 6 also are unavalible) am i doing something fundamentally wrong? or is there actually something missing?

#include <TMC2209.h>

//-----------------------Stepper driver definitions-----------------------

#define StepPin0 PB6
#define StepPin1 PB7
#define StepPin2 PB8
#define StepPin3 PB9

#define DirPin0 PB12
#define DirPin1 PB13
#define DirPin2 PB14
#define DirPin3 PB15


#define AccX 10000
#define AccY 10000
#define AccZ 10000
#define AccA 10000

#define MaxX 100
#define MaxY 200
#define MaxZ 200
#define MaxA 200

#define NUM_STEPPERS 4

#define MicroStepsX 6
#define MicroStepsY 6
#define MicroStepsZ 6
#define MicroStepsA 6

TMC2209 stepper_driver_0;
const TMC2209::SerialAddress SERIAL_ADDRESS_0 = TMC2209::SERIAL_ADDRESS_0;
TMC2209 stepper_driver_1;
const TMC2209::SerialAddress SERIAL_ADDRESS_1 = TMC2209::SERIAL_ADDRESS_1;
TMC2209 stepper_driver_2;
const TMC2209::SerialAddress SERIAL_ADDRESS_2 = TMC2209::SERIAL_ADDRESS_2;
TMC2209 stepper_driver_3;
const TMC2209::SerialAddress SERIAL_ADDRESS_3 = TMC2209::SERIAL_ADDRESS_3;

const uint8_t REPLY_DELAY = 50;





struct stepperInfo {
  // externally defined parameters
  float acceleration;
  volatile unsigned long minStepInterval; // ie. max speed, smaller is faster
  void (*dirFunc)(int);
  void (*stepFunc)();

  // derived parameters
  unsigned int c0;                // step interval for first step, determines acceleration
  long stepPosition;              // current position of stepper (total of all movements taken so far)

  // per movement variables (only changed once per movement)
  volatile int dir;                        // current direction of movement, used to keep track of position
  volatile unsigned int totalSteps;        // number of steps requested for current movement
  volatile bool movementDone = false;      // true if the current movement has been completed (used by main program to wait for completion)
  volatile unsigned int rampUpStepCount;   // number of steps taken to reach either max speed, or half-way to the goal (will be zero until this number is known)
  volatile unsigned long estStepsToSpeed;  // estimated steps required to reach max speed
  volatile unsigned long estTimeForMove;   // estimated time (interrupt ticks) required to complete movement
  volatile unsigned long rampUpStepTime;
  volatile float speedScale;               // used to slow down this motor to make coordinated movement with other motors

  // per iteration variables (potentially changed every interrupt)
  volatile unsigned int n;                 // index in acceleration curve, used to calculate next interval
  volatile float d;                        // current interval length
  volatile unsigned long di;               // above variable truncated
  volatile unsigned int stepCount;         // number of steps completed in current movement
};



void xStep() {
  digitalWrite(StepPin0, HIGH);
  digitalWrite(StepPin0, LOW);
}
void xDir(int dir) {
  digitalWrite(DirPin0, dir);
}
void yStep() {
  digitalWrite(StepPin1, HIGH);
  digitalWrite(StepPin1, LOW);
}
void yDir(int dir) {
  digitalWrite(DirPin1, dir);
}
void zStep() {
  digitalWrite(StepPin2, HIGH);
  digitalWrite(StepPin2, LOW);
}
void zDir(int dir) {
  digitalWrite(DirPin2, dir);
}
void aStep() {
  digitalWrite(StepPin3, HIGH);
  digitalWrite(StepPin3, LOW);
}
void aDir(int dir) {
  digitalWrite(DirPin3, dir);
}

//-----------------------Stepper driver definitions-----------------------

const uint8_t RUN_CURRENT_PERCENT_0 = 100;
const uint8_t RUN_CURRENT_PERCENT_1 = 100;
const uint8_t RUN_CURRENT_PERCENT_2 = 10;
const uint8_t RUN_CURRENT_PERCENT_3 = 50;

const uint8_t STALL_GUARD_THRESHOLD = 50;


const uint8_t MICROSTEPS_PER_STEP_EXPONENT_MIN = 0;
const uint8_t MICROSTEPS_PER_STEP_EXPONENT_MAX = 8;
const uint8_t MICROSTEPS_PER_STEP_EXPONENT_INC = 1;

uint8_t microsteps_per_step_exponent = MICROSTEPS_PER_STEP_EXPONENT_MIN;



const long SERIAL_BAUD_RATE = 115200;

const int DELAY = 1000;

//HardwareSerial Serial(PA10, PA9);
HardwareSerial Serial2 (PA2, PA3);

void resetStepperInfo( stepperInfo& si ) {
  si.n = 0;
  si.d = 0;
  si.di = 0;
  si.stepCount = 0;
  si.rampUpStepCount = 0;
  si.rampUpStepTime = 0;
  si.totalSteps = 0;
  si.stepPosition = 0;
  si.movementDone = false;
}

volatile stepperInfo steppers[NUM_STEPPERS];


//Step pins on TIM4
TIM_TypeDef *Instance = (TIM_TypeDef *)pinmap_peripheral(digitalPinToPinName(StepPin0), PinMap_PWM);
uint32_t channel = STM_PIN_CHANNEL(pinmap_function(digitalPinToPinName(StepPin0), PinMap_PWM));
HardwareTimer *TimerSteppers = new HardwareTimer(Instance);

void setup()
{
  pinMode(PC13, OUTPUT);
  digitalWrite(PC13, HIGH);
  delay(100);
  digitalWrite(PC13, LOW);
  delay(100);
  digitalWrite(PC13, HIGH);
  delay(100);
  digitalWrite(PC13, LOW);
  uint32_t PrescalerFactor = 64;
  TimerSteppers->pause();
  TimerSteppers->setCount(1);
  TimerSteppers->setPrescaleFactor(PrescalerFactor);
  TimerSteppers->setOverflow(1000);
  TimerSteppers->attachInterrupt(Step);
  TimerSteppers->resume();

  steppers[0].dirFunc = xDir;
  steppers[0].stepFunc = xStep;
  steppers[0].acceleration = AccX;
  steppers[0].minStepInterval = MaxX;

  steppers[1].dirFunc = yDir;
  steppers[1].stepFunc = yStep;
  steppers[1].acceleration = AccY;
  steppers[1].minStepInterval = MaxA;

  steppers[2].dirFunc = zDir;
  steppers[2].stepFunc = zStep;
  steppers[2].acceleration = AccZ;
  steppers[2].minStepInterval = MaxZ;

  steppers[3].dirFunc = aDir;
  steppers[3].stepFunc = aStep;
  steppers[3].acceleration = AccA;
  steppers[3].minStepInterval = MaxA;

  Serial.begin(9600);
  StepperDriverSetups(-1);
  checkStepperDriveComms();


}

void resetStepper(volatile stepperInfo& si) {
  si.c0 = si.acceleration;
  si.d = si.c0;
  si.di = si.d;
  si.stepCount = 0;
  si.n = 0;
  si.rampUpStepCount = 0;
  si.movementDone = false;
  si.speedScale = 1;

  float a = si.minStepInterval / (float)si.c0;
  a *= 0.676;

  float m = ((a * a - 1) / (-2 * a));
  float n = m * m;

  si.estStepsToSpeed = n;
}

volatile byte remainingSteppersFlag = 0;

float getDurationOfAcceleration(volatile stepperInfo& s, unsigned int numSteps) {
  float d = s.c0;
  float totalDuration = 0;
  for (unsigned int n = 1; n < numSteps; n++) {
    d = d - (2 * d) / (4 * n + 1);
    totalDuration += d;
  }
  return totalDuration;
}

void prepareMovement(int whichMotor, long steps) {
  volatile stepperInfo& si = steppers[whichMotor];
  si.dirFunc( steps < 0 ? HIGH : LOW );
  si.dir = steps > 0 ? 1 : -1;
  si.totalSteps = abs(steps);
  resetStepper(si);

  remainingSteppersFlag |= (1 << whichMotor);

  unsigned long stepsAbs = abs(steps);

  if ( (2 * si.estStepsToSpeed) < stepsAbs ) {
    // there will be a period of time at full speed
    unsigned long stepsAtFullSpeed = stepsAbs - 2 * si.estStepsToSpeed;
    float accelDecelTime = getDurationOfAcceleration(si, si.estStepsToSpeed);
    si.estTimeForMove = 2 * accelDecelTime + stepsAtFullSpeed * si.minStepInterval;
  }
  else {
    // will not reach full speed before needing to slow down again
    float accelDecelTime = getDurationOfAcceleration( si, stepsAbs / 2 );
    si.estTimeForMove = 2 * accelDecelTime;
  }
}


volatile byte nextStepperFlag = 0;

void setNextInterruptInterval() {

  bool movementComplete = true;

  unsigned long mind = 999999;
  for (int i = 0; i < NUM_STEPPERS; i++) {
    if ( ((1 << i) & remainingSteppersFlag) && steppers[i].di < mind ) {
      mind = steppers[i].di;
    }
  }

  nextStepperFlag = 0;
  for (int i = 0; i < NUM_STEPPERS; i++) {
    if ( ! steppers[i].movementDone )
      movementComplete = false;
    if ( ((1 << i) & remainingSteppersFlag) && steppers[i].di == mind )
      nextStepperFlag |= (1 << i);
  }

  if ( remainingSteppersFlag == 0 ) {
    TimerSteppers->pause();
    TimerSteppers->setOverflow(65500);
  }

  TimerSteppers->setOverflow(mind);
}

void Step() {
  unsigned int tmpCtr = TimerSteppers->getOverflow();

  TimerSteppers->setOverflow(65500);

  for (int i = 0; i < NUM_STEPPERS; i++) {

    if ( ! ((1 << i) & remainingSteppersFlag) )
      continue;

    if ( ! (nextStepperFlag & (1 << i)) ) {
      steppers[i].di -= tmpCtr;
      continue;
    }

    volatile stepperInfo& s = steppers[i];

    if ( s.stepCount < s.totalSteps ) {
      s.stepFunc();
      s.stepCount++;
      s.stepPosition += s.dir;
      if ( s.stepCount >= s.totalSteps ) {
        s.movementDone = true;
        remainingSteppersFlag &= ~(1 << i);
      }
    }

    if ( s.rampUpStepCount == 0 ) {
      s.n++;
      s.d = s.d - (2 * s.d) / (4 * s.n + 1);
      if ( s.d <= s.minStepInterval ) {
        s.d = s.minStepInterval;
        s.rampUpStepCount = s.stepCount;
      }
      if ( s.stepCount >= s.totalSteps / 2 ) {
        s.rampUpStepCount = s.stepCount;
      }
      s.rampUpStepTime += s.d;
    }
    else if ( s.stepCount >= s.totalSteps - s.rampUpStepCount ) {
      s.d = (s.d * (4 * s.n + 1)) / (4 * s.n + 1 - 2);
      s.n--;
    }

    s.di = s.d * s.speedScale; // integer
  }

  setNextInterruptInterval();

  TimerSteppers->setCount(1);
}

void runAndWait() {
  adjustSpeedScales();
  setNextInterruptInterval();
  TimerSteppers->resume();
  while ( remainingSteppersFlag );
  remainingSteppersFlag = 0;
  nextStepperFlag = 0;
}

void adjustSpeedScales() {
  float maxTime = 0;

  for (int i = 0; i < NUM_STEPPERS; i++) {
    if ( ! ((1 << i) & remainingSteppersFlag) )
      continue;
    if ( steppers[i].estTimeForMove > maxTime )
      maxTime = steppers[i].estTimeForMove;
  }

  if ( maxTime != 0 ) {
    for (int i = 0; i < NUM_STEPPERS; i++) {
      if ( ! ( (1 << i) & remainingSteppersFlag) )
        continue;
      steppers[i].speedScale = maxTime / steppers[i].estTimeForMove;
    }
  }
}

void loop() {
  uint16_t stall_guard_result_0 = stepper_driver_0.getStallGuardResult();
  uint16_t stall_guard_result_1 = stepper_driver_1.getStallGuardResult();
  uint16_t stall_guard_result_2 = stepper_driver_2.getStallGuardResult();

  Serial.print("stall_guard_threshold = ");
  Serial.println(STALL_GUARD_THRESHOLD);


  Serial.print("stall_guard_result 0 = ");
  Serial.println(stall_guard_result_0);
  Serial.print("stall_guard_result 1 = ");
  Serial.println(stall_guard_result_1);
  Serial.print("stall_guard_result 2 = ");
  Serial.println(stall_guard_result_2);

  Serial.print("getMicrostepsPerStep() = ");
  Serial.println(stepper_driver_0.getMicrostepsPerStep());
  delay(DELAY);

  uint32_t interstep_duration = stepper_driver_0.getInterstepDuration();
  Serial.print("interstep_duration = ");
  Serial.println(interstep_duration);
  Serial.println();
  digitalWrite(PC13, digitalRead(PC13));

  prepareMovement( 0, 4000 );
  runAndWait();
  prepareMovement( 0, -4000 );
  runAndWait();


}
void checkStepperDriveComms() {
  if (stepper_driver_0.isCommunicatingButNotSetup()) {
    Serial.println("Communication driver 0 is Good");
    StepperDriverSetups(0);
  }
  else if (stepper_driver_0.isSetupAndCommunicating())
  {
    Serial.println("Stepper driver 0 is Setup");
  }


  if (stepper_driver_1.isCommunicatingButNotSetup()) {
    Serial.println("Communication driver 1 is Good");
    StepperDriverSetups(1);
  }
  else if (stepper_driver_1.isSetupAndCommunicating())
  {
    Serial.println("Stepper driver 1 is Setup");
  }


  if (stepper_driver_2.isCommunicatingButNotSetup()) {
    Serial.println("Communication driver 2 is Good");
    StepperDriverSetups(2);
  }
  else if (stepper_driver_2.isSetupAndCommunicating())
  {
    Serial.println("Stepper driver 2 is Setup");
  }


  if (stepper_driver_3.isCommunicatingButNotSetup()) {
    Serial.println("Communication driver 3 is Good");
    StepperDriverSetups(3);
  }
  else if (stepper_driver_3.isSetupAndCommunicating())
  {
    Serial.println("Stepper driver 3 is Setup");
  }
}


void StepperDriverSetups(int Driver) {

  pinMode(StepPin0, OUTPUT);
  pinMode(DirPin0, OUTPUT);
  pinMode(StepPin1, OUTPUT);
  pinMode(DirPin1, OUTPUT);
  pinMode(StepPin2, OUTPUT);
  pinMode(DirPin2, OUTPUT);
  pinMode(StepPin3, OUTPUT);
  pinMode(DirPin3, OUTPUT);

  stepper_driver_0.setup(Serial2, SERIAL_BAUD_RATE, SERIAL_ADDRESS_0);
  stepper_driver_0.setReplyDelay(REPLY_DELAY);

  stepper_driver_1.setup(Serial2, SERIAL_BAUD_RATE, SERIAL_ADDRESS_1);
  stepper_driver_1.setReplyDelay(REPLY_DELAY);

  stepper_driver_2.setup(Serial2, SERIAL_BAUD_RATE, SERIAL_ADDRESS_2);
  stepper_driver_2.setReplyDelay(REPLY_DELAY);

  stepper_driver_3.setup(Serial2, SERIAL_BAUD_RATE, SERIAL_ADDRESS_3);
  stepper_driver_3.setReplyDelay(REPLY_DELAY);

  if (Driver == 0 || Driver == -1) {

    stepper_driver_0.setup(Serial2, SERIAL_BAUD_RATE, SERIAL_ADDRESS_0);
    stepper_driver_0.setReplyDelay(REPLY_DELAY);
    stepper_driver_0.setRunCurrent(RUN_CURRENT_PERCENT_0);
    stepper_driver_0.setStallGuardThreshold(STALL_GUARD_THRESHOLD);
    stepper_driver_0.enableCoolStep();
    stepper_driver_0.setMicrostepsPerStepPowerOfTwo(microsteps_per_step_exponent);
    stepper_driver_0.enableAutomaticCurrentScaling();
    stepper_driver_0.enableAutomaticGradientAdaptation();
    stepper_driver_0.setMicrostepsPerStepPowerOfTwo(MicroStepsX);
    stepper_driver_0.enable();
    delay(10);
  }

  if (Driver == 1 || Driver == -1) {

    stepper_driver_1.setup(Serial2, SERIAL_BAUD_RATE, SERIAL_ADDRESS_1);
    stepper_driver_1.setReplyDelay(REPLY_DELAY);
    stepper_driver_1.setRunCurrent(RUN_CURRENT_PERCENT_1);
    stepper_driver_1.enableCoolStep();
    stepper_driver_1.setStallGuardThreshold(STALL_GUARD_THRESHOLD);
    stepper_driver_1.setMicrostepsPerStepPowerOfTwo(microsteps_per_step_exponent);
    stepper_driver_1.enableAutomaticCurrentScaling();
    stepper_driver_1.enableAutomaticGradientAdaptation();
    stepper_driver_1.setMicrostepsPerStepPowerOfTwo(MicroStepsY);
    stepper_driver_1.enable();
    delay(10);
  }

  if (Driver == 2 || Driver == -1) {

    stepper_driver_2.setup(Serial2, SERIAL_BAUD_RATE, SERIAL_ADDRESS_2);
    stepper_driver_2.setReplyDelay(REPLY_DELAY);
    stepper_driver_2.setRunCurrent(RUN_CURRENT_PERCENT_2);
    stepper_driver_2.enableCoolStep();
    stepper_driver_2.setMicrostepsPerStepPowerOfTwo(microsteps_per_step_exponent);
    stepper_driver_2.enableAutomaticCurrentScaling();
    stepper_driver_2.enableAutomaticGradientAdaptation();
    stepper_driver_2.setMicrostepsPerStepPowerOfTwo(MicroStepsZ);
    stepper_driver_2.enable();
    delay(10);
  }

  if (Driver == 3 || Driver == -1) {

    stepper_driver_3.setup(Serial2, SERIAL_BAUD_RATE, SERIAL_ADDRESS_3);
    stepper_driver_3.setReplyDelay(REPLY_DELAY);
    stepper_driver_3.setRunCurrent(RUN_CURRENT_PERCENT_3);
    stepper_driver_3.enableCoolStep();
    stepper_driver_3.setMicrostepsPerStepPowerOfTwo(microsteps_per_step_exponent);
    stepper_driver_3.enableAutomaticGradientAdaptation();
    stepper_driver_3.enableAutomaticCurrentScaling();
    stepper_driver_3.setMicrostepsPerStepPowerOfTwo(MicroStepsA);
    stepper_driver_3.enable();
    delay(10);
  }
}

Contomo avatar Jul 16 '23 15:07 Contomo

Hi @Contomo Don't know how you met this but TIM4 is well defined for mcu with it.

https://github.com/stm32duino/Arduino_Core_STM32/blob/main/system/Drivers/CMSIS/Device/ST/STM32F1xx/Include/stm32f103xb.h#L650 https://github.com/stm32duino/Arduino_Core_STM32/blob/8ff274affbbce42f1d452e74365b66ba03e66c6c/system/Drivers/CMSIS/Device/ST/STM32F1xx/Include/stm32f103xe.h#L836 https://github.com/stm32duino/Arduino_Core_STM32/blob/8ff274affbbce42f1d452e74365b66ba03e66c6c/system/Drivers/CMSIS/Device/ST/STM32F1xx/Include/stm32f103xg.h#L849

Only this one has no TIM4: https://github.com/stm32duino/Arduino_Core_STM32/blob/main/system/Drivers/CMSIS/Device/ST/STM32F1xx/Include/stm32f103x6.h

Maybe you select the wrong target.

fpistm avatar Jul 17 '23 08:07 fpistm

image found in C:\Users\UserName\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.6.0\variants\STM32F1xx\F103C4T_F103C6(T-U)

why is there no pins mapped to timer4? like PB6-PB9 dont exist

Contomo avatar Jul 17 '23 16:07 Contomo

ok yeah definetly me being sleep deprived, sorry for that, apparently my microcontroller actually has no TIM4....

Contomo avatar Jul 17 '23 16:07 Contomo

image found in C:\Users\UserName\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.6.0\variants\STM32F1xx\F103C4T_F103C6(T-U)

why is there no pins mapped to timer4? like PB6-PB9 dont exist

Those files are automatically generated from the https://github.com/STMicroelectronics/STM32_open_pin_data files. So if not present here, they are not referenced for this mcu that's all. If you look at the datasheet: https://www.st.com/en/microcontrollers-microprocessors/stm32f103c6.html there is no TIM4.

fpistm avatar Jul 17 '23 16:07 fpistm