http://www.51hei.com/ziliao/51hei-5/精准控制步进电机.rar
/*******************51hei************************ 硬件结构框架: 1,MCU STC89C52 2,步进电机驱动芯片ULN2003 显示效果: 1,电机的方向可改变 ************************************************/ #include"AT89x52.h" #define uint unsigned int #define uchar unsigned char
uchar plus[]={0x01,0x03,0x02,0x06,0x04,0x0c,0x08,0x09,0x00}; //电机正转 uchar minu[]={0x08,0x0c,0x04,0x06,0x02,0x03,0x01,0x09,0x00}; //电机反转
sbit key1=P3^1; bit flag; uchar idata *x;
void control(bit cf,uchar n) //电机控制函数,返回变量为方向和步数 { uchar i; if(cf==0)x=plus; //改变电机方向 else x=minu; for(i=0;i<n;i++) //记录电机的步数 { while(flag==0); flag=0; } }
void init() //初始化,开定时器0 { TMOD=0x01; TCON=0x10; TH0=(65536-5000)/256; TL0=(65536-5000)%256; IE=0x82; }
void timer0() interrupt 1 { static uchar i; if(i++>1) //改变电机的速度 { i=0; flag=1; //设置中断标志 P1=*x++; //数组地址加1 if(*x==0)x=x-8; //判断8个控制字后恢复初值 } TH0=(65536-5000)/256; TL0=(65536-5000)%256; }
void main() { init(); while(1) { control(0,200); //电机正转 control(1,200); //电机反转 } } |