|
#include <reg52.h>
typedef unsigned char uchar;
uchar direction = 0; //0為正轉(zhuǎn),1為反轉(zhuǎn)
uchar onoff = 0; //關(guān)為0,開為1
uchar n = 0; //每次定時(shí)器中斷觸發(fā)時(shí)n++,當(dāng)n==max時(shí)電機(jī)轉(zhuǎn)動(dòng)1/4
uchar max = 10;
uchar index = 0; //通過index指示電機(jī)轉(zhuǎn)動(dòng),AB,BC,CD,DA
sbit LED1 = P1 ^ 0;
sbit LED2 = P1 ^ 1;
sbit LED3 = P1 ^ 2;
sbit k_z = P3 ^ 3;
sbit k_f = P3 ^ 4;
sbit k_t = P3 ^ 6;
/*int main()
{
P0 = 0xff;
// 初始化中斷
EA = 1;
EX0 = 1; //要用到的中斷是兩個(gè)外部中斷和定時(shí)器中斷0
IT0 = 1;
EX1 = 1;
IT1 = 1;
ET0 = 1;
//定時(shí)器0
TMOD = 0x01; //使用定時(shí)器0,方式1
TH0 = (65536 - 10000) / 256; //12MHz晶振下,定時(shí)器為10ms觸發(fā)中斷,更方便觀察轉(zhuǎn)動(dòng)情況
TL0 = (65536 - 10000) % 256;
TR0 = 1;
while(1)
{
switch(P3)
{
case 0xfe: //11111110
max = 1;
P0 = 1;
break;
case 0xfd: //11111101
max = 10;
P0 = 2;
break;
case 0xfb: //11111011
max = 50;
P0 = 3;
break;
case 0xf7: //11110111
max = 100;
P0 = 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) //在開狀態(tài)下
{
if (n == max) //設(shè)定檔位速度,經(jīng)過了max次中斷后,步進(jìn)電機(jī)轉(zhuǎn)1/4圈
{
//LED = 0; //每次n==max時(shí)LED閃爍
delay50ms();
//LED = 1;
if (k_z == 0)
{
P1=0xfe;
switch(index) //正轉(zhuǎn)時(shí)以AB,BC,CD,DA順序
{
case 0:P0 = 0x03;break; //00000011 AB高電平
case 1:P0 = 0x06;break; //00000110 BC高電平
case 2:P0 = 0x0c;break; //00001100 CD高電平
case 3:P0 = 0x09;break; //00001001 DA高電平
}
index ++;
if (index == 4) //步進(jìn)電機(jī)轉(zhuǎn)完一圈時(shí)index清零
index = 0;
n = 0; //到達(dá)max,n重置為0
}
if (k_f ==0)
{
P1=0x00;
switch(index) //反轉(zhuǎn)時(shí)以DA,CD,BC,AB順序
{
case 0:P0 = 0x09;break;
case 1:P0 = 0x0c;break;
case 2:P0 = 0x06;break;
case 3:P0 = 0x03;break;
}
index ++;
if (index == 4)
index = 0;
n = 0;
}
else n = 0;
}
n++; //n!=max時(shí),n++
}
else n = 0; //在關(guān)狀態(tài)下,n始終為0,無法觸發(fā)電機(jī)轉(zhuǎn)動(dòng)
}
|
|