Stepper Motor DDS frequency calculations ?

hi,

can somone help me with controlling steppers with dds technique ?
I have read all forum posts that i could find here about dds, but still i dont understand it 100%.

First things first:

  • i’am using arduino mega
  • my stepper motors are nema17 2Nm 2A
  • driver tb6560
  • i want to drive 3 of them
  • i’am using microstepping (1600steps/360deg)
  • timer interrupt is initialized with Timer1 lib

My interrupt function is based on MarkT (thank you for sharing your knowledge :)) code snippets from this forum posts.

Right know it looks like this:

void ddsMotors(void)
{

  for (byte i = 0; i < Nmotor; i++)
  {
    long new_phase = phase[i] + frequency[i] ;  // phase accumulate
    if ((phase[i] ^ new_phase) < 0L)  // sign bit changed, time to step (2 steps per wrap-around)
    {
   
      PORTB |= (1<<step_pins[i]);

    }
    phase[i] = new_phase ;
  }

  for (byte i = 0 ; i < Nmotor ; i++)
  {
    PORTB &= ~(1<<step_pins[i]);
  } 

}

My problem is with frequency calculation - how do i do it ? I tried like this (trial and error / web snippets):

void setSpeed (byte motor, long freq)
{
  noInterrupts () ;
  frequency[motor] = (long)((pow(2, 32) * (float)freq / 10));  //2 for 20Khz interrupt ?
  interrupts () ;
}

and for

Timer1(100); //100us 

setSpeed(0, 1);
setSpeed(1, 1);
setSpeed(2, 1);

motors running great, but as soon as i change one of values (e.g setSpeed(1,4)), everything is getting jittery, and not only for one motor, but for all of them.

What am i doing wrong ?

Post the entire sketch, i may be able to take a look tomorrow when im not in a field camping!

hi, heres my entire sketch:

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"

#include <TimerOne.h>

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

//debug
#define DEBUG

MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

#define OUTPUT_READABLE_YAWPITCHROLL
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// ================================================================
// ===               STEPPER MOTORS CONFIGURATION               ===
// ================================================================

//200 kroków, podział na 8 microstepów = 1600 kroków

const int stepPin1 = PB5; //11; //PB5
const int dirPin1 = 3; 
const int stepPin2 = PB6; //12; //PB6 
const int dirPin2 = 4;
const int stepPin3 = PB7; //13; //PB7
const int dirPin3 = 5; 
int incomingByte = 0; 
int stepVal = LOW;
int16_t motor_speed[3];
uint8_t motor_dir[3];

int counter_m[3];     // counters for periods

#define Nmotor 3
volatile long phase[Nmotor];
volatile long frequency[Nmotor];
byte step_pins[Nmotor] =  { PB5, PB6, PB7 } ;    // step pins for each motor
byte dir_pins[Nmotor]  =  { PE5, PG5, PE3 } ;    // direction pins for each motor


// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    #ifdef DEBUG
      Serial.begin(115200);
      while (!Serial); // wait for Leonardo enumeration, others continue immediately
    #endif

    // initialize device
    #ifdef DEBUG
      Serial.println(F("Initializing I2C devices..."));
    #endif
    mpu.initialize();

    // verify connection
    #ifdef DEBUG
      Serial.println(F("Testing device connections..."));
      Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
    #endif

    // wait for ready
    #ifdef DEBUG
      Serial.println(F("\nSend any character to begin DMP programming and demo: "));
      while (Serial.available() && Serial.read()); // empty buffer
      while (!Serial.available());                 // wait for data
      while (Serial.available() && Serial.read()); // empty buffer again
    #endif

    // load and configure the DMP
    #ifdef DEBUG
    Serial.println(F("Initializing DMP..."));
    #endif
    devStatus = mpu.dmpInitialize();

    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        #ifdef DEBUG
          Serial.println(F("Enabling DMP..."));
        #endif
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        #ifdef DEBUG
          Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        #endif
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        #ifdef DEBUG
          Serial.println(F("DMP ready! Waiting for first interrupt..."));
        #endif
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();

    } else {
        #ifdef DEBUG
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
        #endif
    }

    //init steppers
    init_steppers();

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}



// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    if (!dmpReady) return;

    while (!mpuInterrupt && fifoCount < packetSize) {
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    fifoCount = mpu.getFIFOCount();

    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        mpu.resetFIFO();
        #ifdef DEBUG
          Serial.println(F("FIFO overflow!"));
        #endif
    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {

        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        mpu.getFIFOBytes(fifoBuffer, packetSize);
   
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        #endif
    }
}

// ================================================================
// ===                    INIT STEPPERS PINS                    ===
// ================================================================

void init_steppers()
{

  //dirPIN HIGH -> CCW
  //dirPIN LOW -> CW
  
  pinMode(22,OUTPUT); 
  digitalWrite(22,LOW);
  pinMode(11,OUTPUT); 
  pinMode(dirPin1,OUTPUT);
  pinMode(12,OUTPUT); 
  pinMode(dirPin2,OUTPUT);
  pinMode(13,OUTPUT); 
  pinMode(dirPin3,OUTPUT);
  digitalWrite(dirPin3,LOW); 

  Timer1.initialize(20);
  //100us = 0.01mHz
  //100us = 10kHz
  Timer1.attachInterrupt(ddsMotors);

  digitalWrite(dirPin1,LOW); 
  digitalWrite(dirPin2,LOW); 
  digitalWrite(dirPin3,LOW); 

  for (byte i = 0 ; i < Nmotor ; i++)
  {
    phase[i] = 0L ;
    frequency[i] = 0L ;
  }

  setSpeed(0, 50);
  setSpeed(1, 50);
  setSpeed(2, 50);

}

// ================================================================
// ===                       STEP STEPPERS                      ===
// ================================================================


void ddsMotors(void)
{
  
 
  for (byte i = 0; i < Nmotor; i++)
  {
    long new_phase = phase[i] + frequency[i] ;  // phase accumulate
    if ((phase[i] ^ new_phase) < 0L)  // sign bit changed, time to step (2 steps per wrap-around)
    {
      
      //step      
      PORTB |= (1<<step_pins[i]);

    }
    phase[i] = new_phase ;
  }

  for (byte i = 0 ; i < Nmotor ; i++)
  {
    PORTB &= ~(1<<step_pins[i]);
  }
  

}

void setSpeed (byte motor, long freq) // interrupt safe function to change motor speed
{
  noInterrupts () ;
  //frequency = (long)((pow(2, 32) * (float)freq / 10));  ??
  frequency[motor] = (long)((pow(2, 32) * (float)freq / 2)); 
  interrupts () ;
}

hi, after some reading it's starting to work, but i dont get one thing, following code from lab3 (Lab3 - Laboratory for Experimental Computer Science) i dont understand this part:

// const double refclk=31372.549;  // =16MHz / 510
const double refclk=31376.6;      // measured

what is this value and why 16Mhz divided by 510 ?
how did they measure it ?

when using values from this code my steppers work really good, but i still dont understand this code fully.

bump, anyone ? :slight_smile:

//Timer2 Overflow Interrupt Vector, called every 1ms
ISR(TIMER2_OVF_vect) {
  accum += mspeed;

  if (accum >=1000){
      PORTD = B100;    //step high
      accum -=1000;
      PORTD = B000;    //step low
      iflag=1;
  }
  
  TCNT2 = 130;           //Reset Timer to 130 out of 255
  TIFR2 = 0x00;          //Timer2 INT Flag Reg: Clear Timer Overflow Flag
}

Here is some basic DDS code. You want to stay away from longs in interrupt routines.

When mspeed=1, this will send out a pulse at 1hz.
When mspeed=1000, we get 1khz.

No problem using longs in ISRs. For DDS its essential anyway for the resolution.

In the earlier comment the 510 is the PWM cycles for phase-accurate 8 bit PWM which
clocks 3 2 1 0 1 2 3 ... 254 255 254 253 .... 3 2 1 0 1 2 ...

thanks MarkT

so for example if i move from mega (16mhz) to due (84mhz) i still use 510 as a divider for refclk ?

No, 510 is simply the cycle time for phase-accurate 8-bit PWM unit.

For DDS calculations you have to take into account the rate/frequency the DDS is running and
the number of bits in the accumulator - figure out what a unit velocity or acceleration step
represents in real units (steps per second, degrees per second, rpm or whatever), and use
that to pre-scale your input values.