#include <pic.h>
#include <pic16f722.h>
//#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
uint raw;//定时器1的值
uint average[]={0,0,0,0};//按键振荡计数平均值
uint trip[]={370,400,250,320};//按键振荡计数阀值
uchar index=0; //按键标号
uchar keya,keyb,keyc,keyd; //按键状态
uchar COMP1[]={0x00,0x01,0x02,0x03};
void csm_init();
void timer0_init();
void interrupt intcon();
void keyscan();
void main()
{
__CONFIG(0X1034);
TRISC=0X00;
//PORTC=0X55;
GIE=1;
csm_init();
timer0_init();
while(1)
{
keyscan();
}
}
/***********************************************************/
/****************端口初始化*********************************/
/*************************************************************/
void csm_init()
{
TRISB=0X1F;//cps0-5设为输入
ANSELB=0X1F;//CPS0-CPS5设为模拟输入
CPSCON0=0X8C;//打开电容触摸检测,高频率振荡器
//CPSCON1=0X00;//选择电容触摸通道0
}
/*********************************************************/
/*****************timer0做时基,T1门控受T0控制*************/
/***********************************************************/
void timer0_init()
{
OPTION_REG=0XC3;//FOSC/4,高到低边沿跳变时计数,1;16预分频
T0IF=0;//TIMER0中断标志清0
T0IE=1;//使能TIMER0中断
//TMR0=100;
T1CON=0XC5;//TIMER1初始化
T1GCON=0XE1;//门控,受TIMER0溢出控制
TMR1GIF=0;
TMR1GIE=1;
}
/***********************************************************/
/**************取定时器1的值********************************/
/**************平均值实现算法*******************************/
void interrupt intcon()
{
if(T0IF==1)
{
// T0IF=0;
raw=TMR1L+(unsigned int)(TMR1H<<8);
// 按钮判断并置位按钮状态
if(raw<((long)average[index]-(long)trip[index]))
{
switch(index)
{
case 0: keya=1; break;
case 1: keyb=1; break;
case 2: keyc=1; break;
case 3: keyd=1; break;
default: break;
}
}
// 按钮判断并置位按钮状态滞后量选200
else if(raw>((long)average[index]-(long)trip[index]+64))
{
switch(index)
{
case 0: keya=0; break;
case 1: keyb=0; break;
case 2: keyc=0; break;
case 3: keyd=0; break;
default: break;
}
//求平均值
average[index]=average[index]+((long)raw-(long)average[index])/16;
}
//按键通道切换每10ms切换
index=(++index)&0x03;
CPSCON0=COMP1[index];
//清零寄存器为扫描下一通道准备
raw=0;
TMR1L = 0;
TMR1H = 0;
TMR1ON = 1;
T0IF = 0;
TMR0 = 0;
}
//if((TMR1IF)&&(TMR1IE))
//{
//TMR1IF=0;
//TMR1H=0;
//TMR1L=0;
//}
}
void keyscan()
{
if(keya==1)
RC1=0;
else
RC1=1;
if(keyb==1)
RC3=0;
else
RC3=1;
if(keyc==1)
RC4=0;
else
RC4=1;
if(keyd==1)
RC5=0;
else
RC5=1;
}
|