51单片机实现三相六拍的步进电机控制
2019-11-19 来源:51hei
单片机源程序如下
#include #define uchar unsigned char #define uint unsigned int uint speed = 100; //初始转速 uint max = 200; //最慢转速 uint min = 20; //最快转速 sbit swich = P2^0; //总开关 sbit dir = P2^1; //电机旋转方向 sbit le1=P2^6; sbit le2=P2^7; sbit speedadd=P3^2; sbit speedsub=P3^3; unsigned char uca_MotorStep[]={0x01,0x03,0x02,0x06,0x04,0x0C,0x08,0x09}; //励磁电流数组。 uchar leddata[]={ 0x3F, //'0' 0x06, //'1' 0x5B, //'2' 0x4F, //'3' 0x66, //'4' 0x6D, //'5' 0x7D, //'6' 0x07, //'7' 0x7F, //'8' 0x6F, //'9' 0x40, //'-' 0x00, //熄灭 }; void delay1ms(void) //误差 0us { unsigned char a,b,c; for(c=1;c>0;c--) for(b=142;b>0;b--) for(a=2;a>0;a--); } void delay(uint x ) //多功能毫秒延时 { uint i; for(i=0;i delay1ms(); } } void display(void) { if(swich==1) { P0= leddata[11]; delay(1); le2=1; le1=1; delay(1); le2=0; le1=0; } else { if(dir==1) { P0= leddata[11]; delay(1); le2=1; delay(1); le2=0; } else { P0 =leddata[10]; delay(1); le2=1; delay(1); le2=0; } P0=leddata[9-(speed-20)/20]; delay(30); le1=1; delay(5); le1=0; } } void Init_INT0() { EX0=1; //开启外部中断 0 IT0=1; //设置成低电平触发,1为下降沿触发 EX1=1; //开启外部中断 1 IT1=1; //设置成低电平触发,1为下降沿触发 EA=1; //开启总中断 } void Interrupt0_handler() interrupt 0 { EA=0; //首先关闭总中断,以消除按键出现的抖动所产生的干扰 delay(20); //同样是为了消除抖动而产生新的中断 if(speed>min) {speed=speed-20;} //限制最快转速 else {speed=min;} while(speedadd==0); EA=1; //恢复中断 } void Interrupt1_handler() interrupt 2 { EA=0; //首先关闭总中断,以消除按键出现的抖动所产生的干扰 delay(20); //同样是为了消除抖动而产生新的中断 if(speed else {speed=max;} //限制最慢转速 while(speedsub==0); EA=1; //恢复中断 } void main() { int i; //初始化 dir=1; le1=0; le2=0; start: if(swich==0) {Init_INT0();} //总开关开启,初始化中断,开始转动 else {display(); goto start; } if(dir==1) seq: { while(1) { display(); for (i=0; i<8; i++) { P1 = uca_MotorStep[i]; //取数据 delay(speed); //调节转速 } if(dir==0) //是否换向 { delay(5); // 换向延时 goto oppo; //换向 } if(swich==1) //总开关运行中关闭 goto start; //等待开启 } } else oppo: ……………………