/********************************
用定时中断实现步进电机反转两周半
********************************/
#include <reg52.h>
#define uchar unsigned char
#define ulong unsigned long
void Timer0Init(void); //定时器0初始化声明
void MotorAngle(ulong angle); //步进电机角度函数声明
ulong g_Beats = 0; //两周半的节拍数
void main(void)
{
Timer0Init();
MotorAngle(360*2+180); //两周360*2度加半周180度
while (1);
}
void Timer0Init(void)
{
EA = 1;
TMOD |= 0x01;
TH0 = 0xFC; //定时1MS一个节拍
TL0 = 0x18;
ET0 = 1;
TR0 = 1;
}
void MotorAngle(ulong angle)
{
EA = 0; //防止总节拍数没有算完就开启中断,LONG型数所点四个字节,而单片机为8位的。
g_Beats = (angle * 4076) / 360; //计算两周半共有多少节拍
EA = 1;
}
void Timer0Interrupt() interrupt 1
{
static uchar index = 0;
uchar temp;
uchar code BeatCode[8] = {0x0E,0x0C,0x0D,0x09,
0x0B,0x03,0x07,0x06};
TH0 = 0xFC;
TL0 = 0x18;
if (g_Beats != 0)
{
temp = P1; //用temp暂存P1口的值
temp = temp & 0xF0; //只对P1口的低四位进行操作,要保护好高四位
P1= temp | BeatCode[index]; //把节拍数送到P1口的低四位
index ++;
index &= 0x07; //8个节拍后重新归0;
g_Beats --; //节拍数递减1;
}
else
P1 |= 0x0F; //节拍数等于零时,关闭步进电机。
}
|