單片機控制步進電機--基礎簡單實現
單片機控制步進電機程序(含電路原理圖和程序)
1、設計電路:
主要元件:與門AND_5(5路),ULN2003A(放大電壓用來驅動電機),AT89C52,步進電機MOTOR-STEPPER
2、編寫程序:
#include #define uint unsigned int#define uchar unsigned charint state = 0; //定義電機的狀態 state = 1 正轉 state = -1電機反轉 state = 0 電機停止uint time = 50; //定義延時時間int step[8]={0x01,0x03,0x02,0x06,0x04,0x0c,0x08,0x09};//每一步的通電順序//幾個控制開關量sbit drive = P3^5;sbit stop = P3^6;sbit re_drive = P3^7;sbit add = P3^1;sbit reduce = P3^0;//延時程序 x*10msvoid Delay_xms(uint x){ uint i,j; for(i=0;i<x;i++) for(j=0;j<112;j++);//10ms}//反轉void Move_reverse(uint time){ uint i; for(i= 0;i < 8;i++){ P2 = step[i]; Delay_xms(time); }}//正轉void Move(uint time){ int i; for(i= 7;i >= 0;i--){ P2 = step[i]; Delay_xms(time); } }//定義外部中斷INT0的中斷函數 開關量變化時做出反應void ChangeState() interrupt 0{ if(!drive){ state = 1;drive = 1; } if(!stop){ state = 0;stop = 1; } if(!re_drive){ state = -1;re_drive = 1; } if(!add){ time -= 10;add = 1; if(time <= 10) time = 10; } if(!reduce){ time += 10;reduce = 1; if(time >= 100) time = 100; } }void main(){ EA = 1; //EA (IE.7), CPU中斷允許(總允許)位。 EX0 = 1; //EX0(IE.0),外部中斷0允許位 IE0(TCON.1),外部中斷0中斷請求標誌位。 IT0 = 1; //定義下降沿觸發 while(1){ switch(state){ case 1: Move(time); break; case 0: Delay_xms(10); break; case -1: Move_reverse(time); break; } }}
3、運行結果:
推薦閱讀: