PIC入門(mén)4,全功能步進(jìn)電機(jī)實(shí)驗(yàn)
//適合3ePIC實(shí)驗(yàn)板。
#include
#include
//聲明本模塊中所調(diào)用的函數(shù)類(lèi)型
void delay(unsigned int endcount); //延時(shí)函數(shù),延時(shí)為endcount*0.5毫秒
void run(); //步進(jìn)電機(jī)運(yùn)行控制函數(shù)
void stop(); //步進(jìn)電機(jī)停止函數(shù)
//定義變量
unsigned int count; //延時(shí)函數(shù)用計(jì)數(shù)器
static int step_index; //步進(jìn)索引數(shù),值為0-7
static bit turn; //步進(jìn)電機(jī)轉(zhuǎn)動(dòng)方向
static bit stop_flag; //步進(jìn)電機(jī)停止標(biāo)志
static int speedlevel; //步進(jìn)電機(jī)轉(zhuǎn)速參數(shù),數(shù)值越大速度越慢,最小值為1,速度最快
static int steptimecount; //步進(jìn)電機(jī)每步時(shí)長(zhǎng)倒計(jì)數(shù)
static unsigned char powertimecount; //步進(jìn)電機(jī)每步已通電時(shí)間計(jì)數(shù)
void main(void)
{
ADCON1=0B00000110;//設(shè)置RE端口為普通I/O口
TRISE2=0;
TRISC2=0;
TRISC0=0;
TRISC1=0;
step_index = 0;
stop_flag = 0;
steptimecount = 0;
stop();//步進(jìn)電機(jī)停止
T0CS=0;//選擇內(nèi)部指令周期信號(hào)為T(mén)MR0的時(shí)鐘源
PSA=0;//TMR0使用預(yù)分頻器
PS2=0;//預(yù)分頻器分頻比1:16
PS1=1;
PS0=1;
T0IF=0;//清除TMR0中斷標(biāo)記
TMR0=0X65;//TMR0設(shè)置初值
T0IE=1;//TMR0中斷允許
GIE=1; //全局中斷使能
do{
stop_flag=0;
turn = 0;
speedlevel =7;
delay(1000);//延時(shí)2.5秒
speedlevel = 3;
delay(1000);
stop_flag=1;
delay(1000);
stop_flag=0;
turn = 1;
speedlevel = 7;
delay(1000);
speedlevel =3;
delay(1000);
stop_flag=1;
delay(1000);
}while(1);
}
//定時(shí)器0中斷處理
void interrupt clkint(void)
{
TMR0=0X65;//設(shè)定時(shí)每隔2.5MS中斷一次
T0IF=0;//清除TMR0中斷標(biāo)記
count++;
steptimecount--;
if(powertimecount<=1)//每步最短通電時(shí)間5ms
{
powertimecount++;//未達(dá)最大值時(shí)加1
}
if(powertimecount==1)
{
stop();
}
else if(steptimecount<=0)
{
powertimecount=0;
if (stop_flag==1)
{
stop();
}
else
{
steptimecount = speedlevel;
run();
}
}
}
void delay(unsigned int endcount)
{
count=0;
do{}while(count
void run()
{
switch(step_index)
{
case 0:RC2=1;RC0=0;RC1=0;RE2=0;break;
case 1:RC2=1;RC0=1;RC1=0;RE2=0;break;
case 2:RC2=0;RC0=1;RC1=0;RE2=0;break;
case 3:RC2=0;RC0=1;RC1=1;RE2=0;break;
case 4:RC2=0;RC0=0;RC1=1;RE2=0;break;
case 5:RC2=0;RC0=0;RC1=1;RE2=1;break;
case 6:RC2=0;RC0=0;RC1=0;RE2=1;break;
case 7:RC2=1;RC0=0;RC1=0;RE2=1;
}
if (turn==0)
{
step_index++;
if (step_index>7)
step_index=0;
}
else
{
step_index--;
if (step_index<0)
step_index=7;
}
}
void stop()//使步進(jìn)電機(jī)處于停機(jī)狀態(tài)
{
RC2=0;//M1
RC0=0;//M3
RC1=0;//M2
RE2=0;//M4
}