//蓝桥杯GXCT板子
#include "STC15F2K60S2.h"
#include "intrins.h"
sbit beep = P0^6;
sbit a = P2^5;
sbit b = P2^6;
sbit c = P2^7;
sbit trig = P1^0;
sbit echo = P1^1;
#define Y7C {a = b = c = 1;} //dula
#define Y6C {a = 0;b = c = 1;} //wela
#define Y5C {a = c = 1;b = 0;}
#define somenop() {_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();}
unsigned char code table[]={0xc0,0xf9,0xa4,0xb0,0x99,
0x92,0x82,0xf8,0x80,0x90};
unsigned char code position[]={0x01,0x02,0x04};
unsigned char buf[] ={1,2,3}; //Receive Data
unsigned char site = 0;
void delayus(unsigned int x)
{
for(x=12*x;x>0;--x)
{
_nop_(); _nop_(); _nop_(); _nop_();
}
}
void delayms(unsigned int x)
{
unsigned char i,j;
for(;x>0;--x)
{
i = 12; j = 169;
while(i--)
{
while(j--);
}
}
}
void sendWave(void)
{
unsigned char i = 4;
while(i--)
{
trig = 1;
somenop();somenop();somenop();somenop();
trig = 0;
somenop();somenop();somenop();somenop();
}
}
void display(void)
{
P0 = 0x00;
Y7C; //dula
P0 = table[buf[site]];
delayus(1);
Y6C; //wela
P0 = position[site]; //无关数据处理
}
void Seginit(void) //T1用作数码管扫描
{
AUXR = 0x3f; //8051
TMOD = 0x10; //16位
EA = ET1 = TR1 = 1;
TH1 = (65536 - 4608)/256;
TL1 = (65536 - 4608)%256;
}
void HC_init(void) //T0用作HC_SR04
{
TMOD |= 0x01; //16位
EA = ET1 = 1;
TR0 = 0;
TH0 = TL0 = 0;
TF0 = 0;
}
unsigned char flag = 1,count = 0;
main()
{
unsigned int number,distance;
float time;
Y5C; beep = 0;
Seginit();
HC_init();
while(1)
{
if(flag==1) //每200ms测量一次
{
sendWave();
TR0 = 1; TF0 = 0;
while((echo==1) & (TF0==0)); //等待高电平的到来
TR0 = 0;
if(TF0==1)
{
buf[0] = buf[1] = buf[2] = 9;
TF0 = 0;
}
else
{
number = (TH0 << 8) | TL0;
TH0 = TL0 = 0;
time = number*1.085;
distance = (unsigned int)(time*0.17); //340m/s == 340m/1000ms
buf[0] = distance/1000;
buf[1] = distance/100%10;
buf[2] = distance%10;
}
}
flag = 0;
}
}
void T1(void) interrupt 3
{
TH1 = (65536 - 4608)/256; //5ms
TL1 = (65536 - 4608)%256; //5ms
display();
if(++site==3)
site = 0;
if(++count==40) //40*5 = 200ms
{
count = 0;
flag = 1;
}
}
void T0(void) interrupt 1 //T0用作HC_SR04
{
TH0 = TL0 = 0;
TF0 = 0;
}