#includeAT89X51.hstaticunsignedintcount;//计数staticintstep_index;//步进索引数,值为0-7staticbitturn;//步进电机转动方向staticbitstop_flag;//步进电机停止标志staticintspeedlevel;//步进电机转速参数,数值越大速度越慢,最小值为1,速度最快staticintspcount;//步进电机转速参数计数voiddelay(unsignedintendcount);//延时函数,延时为endcount*0.5毫秒voidgorun();//步进电机控制步进函数voidmain(void){count=0;step_index=0;spcount=0;stop_flag=0;P1_0=0;P1_1=0;P1_2=0;P1_3=0;EA=1;//允许CPU中断TMOD=0x11;//设定时器0和1为16位模式1ET0=1;//定时器0中断允许TH0=0xFE;TL0=0x0C;//设定时每隔0.5ms中断一次TR0=1;//开始计数turn=0;speedlevel=2;delay(10000);speedlevel=1;do{speedlevel=2;delay(10000);speedlevel=1;delay(10000);stop_flag=1;delay(10000);stop_flag=0;}while(1);}//定时器0中断处理voidtimeint(void)interrupt1{TH0=0xFE;TL0=0x0C;//设定时每隔0.5ms中断一次count++;spcount--;if(spcount=0){spcount=speedlevel;gorun();}}voiddelay(unsignedintendcount){count=0;do{}while(countendcount);}voidgorun(){if(stop_flag==1){P1_0=0;P1_1=0;P1_2=0;P1_3=0;return;}switch(step_index){case0://0P1_0=1;P1_1=0;P1_2=0;P1_3=0;break;case1://0、1P1_0=1;P1_1=1;P1_2=0;P1_3=0;break;case2://1P1_0=0;P1_1=1;P1_2=0;P1_3=0;break;case3://1、2P1_0=0;P1_1=1;P1_2=1;P1_3=0;break;case4://2P1_0=0;P1_1=0;P1_2=1;P1_3=0;break;case5://2、3P1_0=0;P1_1=0;P1_2=1;P1_3=1;break;case6://3P1_0=0;P1_1=0;P1_2=0;P1_3=1;break;case7://3、0P1_0=1;P1_1=0;P1_2=0;P1_3=1;}if(turn==0){step_index++;if(step_index7)step_index=0;}else{step_index--;if(step_index0)step_index=7;}}