dfd

Dependencies:   stepper mbed

Fork of puma_test by Keegan Hu

Stepper_motor.cpp

Committer:
glintligo
Date:
2018-05-11
Revision:
3:09f6061e6e5d
Parent:
2:ecf401a37aa3

File content as of revision 3:09f6061e6e5d:

#include "Stepper_motor.h"
#include "mbed.h"
extern Serial Info;
/**
 * [Stepper_motor::Stepper_motor 构造函数 初始化一个步进电机对象]
 * @param _en           [en引脚]
 * @param _stepPin      [step引脚]
 * @param _dirPin       [dir引脚]
 * @param Inter         [行程开关引脚]
 * @param _ratio        [减速比]
 * @param _micorstep    [细分数]
 * @param _dir          [初始方向]
 * @param _rec          [步距角]
 */
Stepper_motor::Stepper_motor(PinName _en,PinName _stepPin,PinName _dirPin,PinName Inter,int _ratio,int _micorstep,int _dir,float _rec):Stepper(_en,_stepPin,_dirPin),InterruptIn(Inter)
{
    ratio = _ratio;
    microstep = _micorstep;
    dir = _dir;
    Ori_rec = _rec;
    pos_dir = _dir;
    this->enable();
}
/**
 * [Stepper_motor::Config 步进电机角度速度控制]
 * @param rec_rate [转速 单位deg/s]  
 * @param rec      [转动的角度 单位 °]
 * 若转动的角度为-1 则会一直转,此时rec_rate需大于0
 * 除此之外,若转动角度或转速小于0,则电机反转
 * 如在电机尚未停止前再次调用该函数,则会立刻开始新的电机运动
 */
void Stepper_motor::Config(float rec_rate,float rec)
{
    if(rec < 0 && rec != -1)
    {
        rec_rate = 0 - rec_rate;
        rec = 0 - rec;
    }
    long long int frequency = rec_rate * ratio * microstep / Ori_rec;
    if(frequency < 0)
    {
        dir = 1 - pos_dir;
        frequency = 0 - frequency;
    }
    else if(frequency == 0)
    {
        this->disable();
        return;
    }
    else if(frequency > 0)
    {
        dir = pos_dir;
    }
    long long int remain = rec * ratio * microstep / Ori_rec;
   // Info.printf("remain:%d frequency:%d\n",remain, frequency);
    this->enable();
    this->step(dir,frequency,remain);
    
}
/**
 * [Stepper_motor::getDir 获取电机的转动方向dir]
 * @return [dir]
 */
int Stepper_motor::getDir()
{
    return this->dir;
}

/**
 * [Stepper_motor::reConfig 步进电机反转]
 * @param _rec [反转的角度]
 * 速度为5°/s
 */
void Stepper_motor::reConfig(float _rec)
{   
    dir = 1 - dir;
    long long int frequency = 5 * ratio * microstep / Ori_rec;
    long long int remain = _rec * ratio * microstep / Ori_rec;
    this->enable();
    this->step(dir,frequency,remain);
}

/**
 * [Stepper_motor::set 行程开关按下后的运动函数]
 */
void Stepper_motor::set()
{
    this -> Config(0,0);//停止运动
    wait(0.01);
    this -> enable();
    this -> Config(-5,7);
}

/** [Stepper_motor::Init 步进电机初始化] */
void Stepper_motor::Init()
{
    this->Config(10,-1);
    this->fall(this,&Stepper_motor::set); 
}