#include <STC8G.H>
#include "intrins.h"
#include <stdio.h>
#define FOSC 11059200UL
#define BRT (65536-FOSC/115200/4)
int code yl[12]={349,392,440,494,523,587,659,698,784,880,988,1046};
int code keys[12]={169,234,289,338,575,555,533,509,482,452,418,381};
sbit speaker=P5^4;
bit busy;
void Delay500ms(void) //@11.0592MHz
{
unsigned char data i, j, k;
i = 29;
j = 14;
k = 54;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void UartInit()
{
SCON=0X50;
AUXR|=0X40;
TH1=BRT>>8;
TL1=BRT;
TR1=1;
ES=1;
EA=1;
busy=0;
}
void UartIsr() interrupt 4
{
if(RI)
{
RI=0;
}
if(TI)
{
TI=0;
busy=0;
}
}
void UartSend(char c)
{
while(busy);
busy=1;
SBUF=c;
}
void UartSendStr(char *p)
{
while(*p){
UartSend(*p++);
}
}
void TimerInit()
{
TMOD=0X00;
TH0=0X00;
TL0=0X00;
AUXR|=0X80;
TR0=1;
}
void PWMInit()
{
CCON=0X00;
CMOD=0X04;
CL=0X00;
CH=0X00;
CCAPM2=0X42;
PCA_PWM2=0X80;
CCAP2L=0x10;
CCAP2H=0x10;
}
void ADCInit()
{
P_SW2|=0X80;
ADCTIM=0X3F;
P_SW2&=0X7F;
ADCCFG=0X2F;
ADC_CONTR=0X83;
}
int ADCRead()
{
int res;
ADC_CONTR|=0X40;
_nop_();
_nop_();
while(!(ADC_CONTR&0X20));
ADC_CONTR&=~0X20;
res=(ADC_RES<<8)|ADC_RESL;
return res;
}
void main()
{
P5M0 = 0x00; P5M1 = 0x00;
P3M0 = 0x00; P3M1 = 0x08;
TimerInit();
UartInit();
PWMInit();
ADCInit();
speaker=0;
while(1)
{
char sendStr[30];
int i,j;
int res;
int pwm;
res=0;
for(i=0;i<8;i++)
{
res+=ADCRead();
}
res>>=3;
if(res<580)
{
if(res<keys[0]+5 && res>keys[0]-5)
{
j=0;
}
if(res<keys[1]+5 && res>keys[1]-5)
{
j=1;
}
if(res<keys[2]+5 && res>keys[2]-5)
{
j=2;
}
if(res<keys[3]+5 && res>keys[3]-5)
{
j=3;
}
if(res<keys[4]+5 && res>keys[4]-5)
{
j=4;
}
if(res<keys[5]+5 && res>keys[5]-5)
{
j=5;
}
if(res<keys[6]+5 && res>keys[6]-5)
{
j=6;
}
if(res<keys[7]+5 && res>keys[7]-5)
{
j=7;
}
if(res<keys[8]+5 && res>keys[8]-5)
{
j=8;
}
if(res<keys[9]+5 && res>keys[9]-5)
{
j=9;
}
if(res<keys[10]+5 && res>keys[10]-5)
{
j=10;
}
if(res<keys[11]+5 && res>keys[11]-5)
{
j=11;
}
}else{
j=-1;
TR0=0;
CR=0;
speaker=0;
}
if(j!=-1)
{
TH0=(65536-FOSC/64/yl[j])>>8;
TL0=(65536-FOSC/64/yl[j]);
TR0=1;
CR=1;
}
// sprintf(sendStr,"ADC:%d PWM:%d\n",res,pwm);
// UartSendStr(sendStr);
// Delay500ms();
//
}
}