#include<stc15w408s.h>
#include <intrins.h>
#include<stdio.h>
#define uint unsigned int
#define uchar unsigned char
uint s1;
uint distance;
sbit trig=P0^1;
sbit echo=P0^3;
sbit led=P0^0;
void Delay20us()//@12.000MHz
{
unsigned char i;
_nop_();
_nop_();
i = 57;
while (--i);
}
void UartInit(void)//9600bps@12.000MHz
{
SCON = 0x50;//8位数据,可变波特率
AUXR |= 0x40;//定时器1时钟为Fosc,即1T
AUXR &= 0xFE;//串口1选择定时器1为波特率发生器
TMOD &= 0x0F;//设定定时器1为16位自动重装方式
TL1 = 0xC7;//设定定时初值
TH1 = 0xFE;//设定定时初值
ET1 = 0;//禁止定时器1中断
TR1 = 1;//启动定时器1
REN=1;
ES=1;
}
void Timer0Init(void)//1微秒@12.000MHz
{
AUXR &= 0x7F;//定时器时钟12T模式
TMOD &= 0xF0;//设置定时器模式
TMOD |= 0x02;//设置定时器模式
TL0 = 0xFF;//设置定时初值
TH0 = 0xFF;//设置定时重载值
TF0 = 0;//清除TF0标志
TR0 = 1;//定时器0开始计时
ET0=1;
EA=1; //中断总开关打开
}
void start()//启动超声波
{
trig=1;
Delay20us();
//Delay20us();
trig=0;
}
main()
{
Timer0Init();
UartInit();
while(1)
{
start();//启动
while(echo==1)
{
distance=(s1*17); //算距离
s1=0;
}
ES=0;
TI=1;
printf("%d\n",distance); //串口打印
while(!TI);
TI=0;
ES=1;
}
}
void time0() interrupt 1 //中断计时
{
s1++;
}
#include <intrins.h>
#include<stdio.h>
#define uint unsigned int
#define uchar unsigned char
uint s1;
uint distance;
sbit trig=P0^1;
sbit echo=P0^3;
sbit led=P0^0;
void Delay20us()//@12.000MHz
{
unsigned char i;
_nop_();
_nop_();
i = 57;
while (--i);
}
void UartInit(void)//9600bps@12.000MHz
{
SCON = 0x50;//8位数据,可变波特率
AUXR |= 0x40;//定时器1时钟为Fosc,即1T
AUXR &= 0xFE;//串口1选择定时器1为波特率发生器
TMOD &= 0x0F;//设定定时器1为16位自动重装方式
TL1 = 0xC7;//设定定时初值
TH1 = 0xFE;//设定定时初值
ET1 = 0;//禁止定时器1中断
TR1 = 1;//启动定时器1
REN=1;
ES=1;
}
void Timer0Init(void)//1微秒@12.000MHz
{
AUXR &= 0x7F;//定时器时钟12T模式
TMOD &= 0xF0;//设置定时器模式
TMOD |= 0x02;//设置定时器模式
TL0 = 0xFF;//设置定时初值
TH0 = 0xFF;//设置定时重载值
TF0 = 0;//清除TF0标志
TR0 = 1;//定时器0开始计时
ET0=1;
EA=1; //中断总开关打开
}
void start()//启动超声波
{
trig=1;
Delay20us();
//Delay20us();
trig=0;
}
main()
{
Timer0Init();
UartInit();
while(1)
{
start();//启动
while(echo==1)
{
distance=(s1*17); //算距离
s1=0;
}
ES=0;
TI=1;
printf("%d\n",distance); //串口打印
while(!TI);
TI=0;
ES=1;
}
}
void time0() interrupt 1 //中断计时
{
s1++;
}