#include <reg52.h>
typedef unsigned char uchar;uchar direction = 0; //0为正转,1为反转uchar onoff = 0; //关为0,开为1uchar n = 0; //每次定时器中断触发时n++,当n==max时电机转动1/4uchar max = 10;uchar index = 0; //通过index指示电机转动,AB,BC,CD,DAsbit LED = P3 ^ 7; //当n==max时LED闪烁提示int main(){ /* LED */ P2 = 0xff; /* 初始化中断 */ EA = 1; EX0 = 1; //要用到的中断是两个外部中断和定时器中断0 IT0 = 1; EX1 = 1; IT1 = 1; ET0 = 1; /* 定时器0 */ TMOD = 0x01; //使用定时器0,方式1 TH0 = (65536 - 10000) / 256; //12MHz晶振下,定时器为10ms触发中断,更方便观察转动情况 TL0 = (65536 - 10000) % 256; TR0 = 1; while(1) { switch(P0) { case 0xfe: //11111110 max = 1; P2 = 1; break; case 0xfd: //11111101 max = 10; P2 = 2; break; case 0xfb: //11111011 max = 50; P2 = 3; break; case 0xf7: //11110111 max = 100; P2 = 4; break; } }}void Stop()interrupt 0{ onoff++; if (onoff > 1) onoff = 0;}void int1()interrupt 2{ direction++; if (direction > 1) direction = 0;}void delay50ms(void){ unsigned char a, b; for(b = 173; b > 0; b--) for(a = 143; a > 0; a--);}void time()interrupt 1{ TH0 = (65536 - 10000) / 256; TL0 = (65536 - 10000) % 256; if (onoff == 1) //在开状态下 { if (n == max) //设定档位速度,经过了max次中断后,步进电机转1/4圈 { LED = 0; //每次n==max时LED闪烁 delay50ms(); LED = 1; if (direction == 0) { switch(index) //正转时以AB,BC,CD,DA顺序 { case 0:P1 = 0x03;break; //00000011 AB高电平 case 1:P1 = 0x06;break; //00000110 BC高电平 case 2:P1 = 0x0c;break; //00001100 CD高电平 case 3:P1 = 0x09;break; //00001001 DA高电平 } index ++; if (index == 4) //步进电机转完一圈时index清零 index = 0; n = 0; //到达max,n重置为0 } if (direction == 1) { switch(index) //反转时以DA,CD,BC,AB顺序 { case 0:P1 = 0x09;break; case 1:P1 = 0x0c;break; case 2:P1 = 0x06;break; case 3:P1 = 0x03;break; } index ++; if (index == 4) index = 0; n = 0; } else n = 0; } n++; //n!=max时,n++ } else n = 0; //在关状态下,n始终为0,无法触发电机转动}