5555今天才知道,原来延时14us可以使蓝桥杯单片机的超声波测距更广,反正可以大于80cm
下面附上代码,大家可以直接测试
#include "stc15f2k60s2.h"
#include "intrins.h"
typedef unsigned char u8;
typedef unsigned int u16;
sbit TX = P1^0;
sbit RX = P1^1;
u8 code T_duan[]={ //标准字库
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,0x77,0x7C,0x39,0x5E,0x79,0x71,
//black - H J K L N o P U t G Q r M y
0x00,0x40,0x76,0x1E,0x70,0x38,0x37,0x5C,0x73,0x3E,0x78,0x3d,0x67,0x50,0x37,0x6e,
0xBF,0x86,0xDB,0xCF,0xE6,0xED,0xFD,0x87,0xFF,0xEF,0x46}; //0. 1. 2. 3. 4. 5. 6. 7. 8. 9. -1
u8 code T_COM[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; //位码
u8 smg_i,table[8];
u8 distance;
u16 count; //1000 times counter
bit flag100ms;
//-----------------------------------------------
/* Timer0 interrupt routine */
void tm0_isr() interrupt 1 using 1
{
if (count-- == 0) //1ms * 1000 -> 1s
{
count = 1000; //reset counter
}
if(count %2 == 0)
{
P2 = (P2&0x1f)|0xe0; P0 = ~table[smg_i]; P2 = (P2&0x1f);
P2 = (P2&0x1f)|0xc0; P0 = T_COM[smg_i]; P2 = (P2&0x1f);
smg_i++; smg_i &= 0x07;
}
if(count % 100 == 0) flag100ms = 1;
}
void Timer0Init();
void countT1();
void allint();
void smg_dis();
void Delay14us();
void sendsonic();
void main()
{
Timer0Init();
countT1();
allint();
while (1)
{
if(flag100ms)
{
flag100ms = 0;
sendsonic();
smg_dis();
}
}
}
void Timer0Init(void) //1毫秒@12.000MHz
{
AUXR &= 0x7F; //定时器时钟12T模式
TMOD &= 0xF0; //设置定时器模式
TL0 = 0x18; //设置定时初值
TH0 = 0xFC; //设置定时初值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0 = 1; //enable timer0 interrupt
EA = 1; //open global interrupt switch
count = 0; //initial counter
}
void countT1(void) //1毫秒@12.000MHz
{
AUXR &= 0xBF; //定时器时钟12T模式
TMOD &= 0x0F; //设置定时器模式
TL1 = 0x00; //设置定时初值
TH1 = 0x00; //设置定时初值
TF1 = 0; //清除TF1标志
TR1 = 0; //定时器1开始计时
}
void allint()
{
P2 = (P2&0x1f)|0xa0; P0 = 0x00; P2 = (P2&0x1f);
P2 = (P2&0x1f)|0x80; P0 = 0xff; P2 = (P2&0x1f);
}
void smg_dis()
{
table[0] = T_duan[distance/100%10];
table[1] = T_duan[distance/10%10];
table[2] = T_duan[distance%10];
table[3] = 0x40;
table[4] = 0x40;
table[5] = 0x40;
table[6] = 0x40;
table[7] = 0x40;
}
void Delay14us() //@12.000MHz
{
unsigned char i;
_nop_();
_nop_();
i = 39;
while (--i);
}
void sendsonic()
{
TX = 1; Delay14us(); TX = 0; Delay14us();
TX = 1; Delay14us(); TX = 0; Delay14us();
TX = 1; Delay14us(); TX = 0; Delay14us();
TX = 1; Delay14us(); TX = 0; Delay14us();
TX = 1; Delay14us(); TX = 0; Delay14us();
TX = 1; Delay14us(); TX = 0; Delay14us();
TX = 1; Delay14us(); TX = 0; Delay14us();
TX = 1; Delay14us(); TX = 0; Delay14us();
TR1 = 1;
while(RX == 1&& TF1 == 0);
TR1 = 0;
if(TF1 == 1)
{
distance = 249;
TF1 = 0;
TH1 = 0;
TL1 = 0;
}
if(RX == 0)
{
distance = (TH1<<8|TL1)*0.017;
TH1 = 0;
TL1 = 0;
}
}