您的位置:首页 > 其它

51单片机用定时器中断实现两相四线步进电机时序控制

2018-02-28 14:48 417 查看
#include<reg52.h>
#define iniMotor() (MOTOR=0x00)

sfr MOTOR=0x90;//define the sfr MOTOR is the address of P1 port

static void iniTimer0(); //ini timer 0

static void motorDrive(unsigned char const pul,unsigned char const dir);	//stepper motor drive function

int main(){
/*ini MOTOR(set P1 port to low)*/
iniMotor();
/*ini timer 0*/
iniTimer0();
/*infinite loop,wait to interrupt of T0*/
while(1);
return 0;
}

void iniTimer0(){
EA=1;
ET0=1;  //open the T0 interrupt
TMOD=0x01; //use mode 1:M1M0=01
TR0=1;	//run timer 0
}

void motorDrive(unsigned char const pul,unsigned char const dir){
static unsigned char count;
/*counterclockwise rotation sequential of motor:A- --> B- --> A+ --> B+
clockwise rotation sequential of motor:B+ --> A+ --> B- --> A- */
static unsigned char table[2][4]={{0x01,0x04,0x02,0x08},{0x08,0x02,0x04,0x01}};
/*judge the pulse is high lever or low*/
if(pul)
/*drive the motor,dir is high lever or low:0 is counter clock;1 is clock*/
MOTOR=table[dir][(count++) % 4];
}

/*T0 interrupt function*/
void emitPulse() interrupt 1{
//unsigned short pulse_cycle,wait_time;
static unsigned char pul,dir=1;//pulse,direction for motorDrive():dir=0,counterclock;dir=1,clock
//pulse_cycle=2000;//pulse_cycle is 2000us(2 ms)
//wait_time=pulse_cycle/2;//duty cycle of high speed pulse is 50%,so wait time is 50% of pulse_cycle
TH1=(65536-1000) >> 8;	 //set interrupt time of T0
TL1=(65536-1000);
pul=~pul & 0x01; //if pul=1,pul=0;pul=0,pul=1
motorDrive(pul,dir);//emit pulse
}


           以上程序是有问题的,只是提供一种参考,因为T0中断服务程序执行时间过长,导致定时器中断时效性不是很好(即中断服务程序还未执行完,定时器又溢出了)。

       由于51单片机性能有限,再怎么优化,定时器中断都不是实现步进电机控制的好方法,采用延时子程序对步进电机进行时序控制是相对来讲比较好的方法,时效性比定时器中断好得多。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: