vendredi 30 septembre 2016

Using member variables in static function

I am having some issues with using a member variable within static function. I am trying to code a ramp up signal for stepper motor, that has to run on a arduino uno. The timer1 library available from arduino (http://ift.tt/2dg4Q8W), which interfaces with the timer1. The static function is a callback function which has to called everytime an interrupt occurs. When an interrrupt occurs, should the period time of the next pwm signal be decreased, and the amount it is decreased by is calculated within the interrupt/callback, and how I calulated is currently the problem.

The way i calulate is

uint32_t new_period = sqrt(2*n/4.8);
current_period -= new_period;

In which n should be increased for each completed period. I keep track of n by having it as a member variable inside of the class,

But that will not work, as the callback is a static function, and the variable is a member of the class.

I guess I could make it as a different design pattern - singleton, But there should be a different way to do the same thing, I would not like to use singleton in case of i would have to use multiple motors

Here is the .cpp

#include "stepper_motor.h"

int step_count = 0;
stepper_motor::stepper_motor()
{
  //pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin, OUTPUT);
  pinMode(dir_pin, OUTPUT);
  pinMode(en_pin, OUTPUT);
  alive_bool = true;
  position_bool = false;
  step_count = 0;
  period = 40825UL << 16; // 20412,5 us fixed point arithmetic time = 0

}

static void stepper_motor::callback()
{
  if (step_count < 240)
  {
    uint32_t new_period = sqrt(2 * step_count / 4.8);
    period -= new_period; 
  }
  else
  {
    return;
  }
}


void stepper_motor::step_pwm()
{

  digitalWrite(en_pin, HIGH);

  delay(0.005);

  digitalWrite(dir_pin, HIGH);
  //LOW  - Move towards the sensor
  //HIGH -  Move away from the sensor

  delay(0.005);

  int timestep = 0;

  timer1.initialize(period);
  timer1.attachInterrupt(callback);
}

and the .h file

#ifndef stepper_motor_h
#define stepper_motor_h

#include "Arduino.h"
#include <TimerOne.h>

#define step_pin  13
#define dir_pin   12
#define en_pin    11
#define max_step  200

 class stepper_motor
{
  public:
    stepper_motor();
    void step_pwm();
    static void callback();
    TimerOne timer1;
  private:
    uint32_t period;
    bool alive_bool;    
    //int step_count;
    bool position_bool;
};


#endif

Aucun commentaire:

Enregistrer un commentaire