#include <reg51.h>
#include "51uart.h"
//角度结算时间
int HXA_CALC_TIMES = 1000;
sbit A_PORT = P2^7;
sbit B_PORT = P2^6;
bit A_LAST_STATE;
bit B_LAST_STATE;
//脉冲计算
#define HXA_Pluse_Get_A() (A_LAST_STATE^A_PORT)
#define HXA_Pluse_Fresh_A() (A_LAST_STATE = A_PORT)
#define HXA_Pluse_Get_B() (B_LAST_STATE^B_PORT)
#define HXA_Pluse_Fresh_B() (B_LAST_STATE = B_PORT)
//脉冲统计
#define TIMER_COUNT (6000)
int PluseBCountOld;
int PluseBCount;
int PluseBCountTimer;
#define HXA_Pluse_Fresh_OLD_B() (PluseBCountOld = PluseBCount)
#define HXA_Pluse_B_HAS_COUNT() (PluseBCountOld!= PluseBCount)
#define HXA_Pluse_Fresh_TIMER() (PluseBCountTimer = TIMER_COUNT)
#define HXA_Pluse_Fresh_SUB_TIMER() (--PluseBCountTimer < 0 ? 0 : PluseBCountTimer)
#define HXA_Pluse_Fresh_TIMER_OUT() (PluseBCountTimer == 0)
int dir;
//XHA 状态
#define XHA_SENDING 1
#define XHA_WAIT 0
int XHA_Status = XHA_WAIT;
int main()
{
BYTE Count = 0;
uartInit(BAUD_9600);
SendString("system Init!\n");
HXA_Pluse_Fresh_A();
HXA_Pluse_Fresh_B();
HXA_Pluse_Fresh_OLD_B();
HXA_Pluse_Fresh_TIMER();
PluseBCount = 0;
P2=P2|(0x30);
while(1)
{
/*---------------------------对光电编码器进行计数-----------------------------------------*/
dir = -1;
//------------------------A脉冲------------------------------------------
if(HXA_Pluse_Get_A())
{
//上升沿
if(A_PORT == 1 && B_PORT == 1)
{
dir = 1;
++PluseBCount;
}
else if(A_PORT == 1 && B_PORT == 0)
{
dir = 0;
--PluseBCount;
}
//下降沿
if(A_PORT == 0 && B_PORT == 0)
{
dir = 1;
++PluseBCount;
}
else if(A_PORT == 0 && B_PORT == 1)
{
dir = 0;
--PluseBCount;
}
HXA_Pluse_Fresh_TIMER();
HXA_Pluse_Fresh_A();
continue;
}
else
{
HXA_Pluse_Fresh_SUB_TIMER();
}
//-------------------------------B脉冲------------------------------------
if(HXA_Pluse_Get_B())
{
//上升沿
if(B_PORT == 1 && A_PORT == 0)
{
dir = 1;
++PluseBCount;
}
else if(B_PORT == 1 && A_PORT == 1)
{
dir = 0;
--PluseBCount;
}
//下降沿
if(B_PORT == 0 && A_PORT == 1)
{
dir = 1;
++PluseBCount;
}
else if(B_PORT == 0 && A_PORT == 0)
{
dir = 0;
--PluseBCount;
}
HXA_Pluse_Fresh_TIMER();
HXA_Pluse_Fresh_B();
continue;
}
else
{
HXA_Pluse_Fresh_SUB_TIMER();
}
//--------------外接P2^4,P^5作为测试led ---------------------
if(dir == 1)
{
P2=P2&~(0x20);
P2=P2|0x10;
}
else if(dir == 0)
{
P2=P2&~(0x10);
P2=P2|0x20;
}
else
{
P2=P2&~(0x30);
}
//--------------- 串口发送模块------------------------------------
if(HXA_Pluse_Fresh_TIMER_OUT())
{
XHA_Status = XHA_SENDING;
HXA_Pluse_Fresh_TIMER();
}
else
{
XHA_Status = XHA_WAIT;
continue;
}
if(XHA_Status == XHA_SENDING && PluseBCount!=0)
{
Count = PluseBCount>=0?0:0xFF;
SendData(Count);
if(PluseBCount<0)
{
PluseBCount = 0 - PluseBCount;
}
Count = (PluseBCount>>16)&0xff;
SendData(Count);
Count = (PluseBCount>>8)&0xff;
SendData(Count);
Count = PluseBCount&0xff;
SendData(Count);
PluseBCount = 0;
}
}
}
|