#include <reg52.h>
#include <stdio.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit Trig = P3^4; //超声波控制端
sbit Echo = P3^5; //超声波接收端
sbit led = P1^0; //指示灯
sbit led1 = P3^2; //红外感应
sbit beep = P2^3; //蜂鸣器
sbit servorControl = P1^3; //舵机的控制引脚
uchar flag = 0;
uchar control = 0; //舵机控制变量
uchar servorTime =0;
unsigned char T0RH =0;
unsigned char T0RL =0;
void delay (unsigned int z)//毫秒级延时
{
unsigned int x,y;
for(x = z; x > 0; x--)
for(y = 114; y > 0 ; y--);
}
//初始化定时器
void Delay_us(unsigned char t)
{
while(--t);
} //大约延时t*2+5us 超声波模块用
void timer0() interrupt 1
{
TH0 = 0;
TL0 = 0;
}
//中断程序初始化赋值 重新计数 超声波模块用 计算时间
//void time_init()
//{
// TMOD |= 0x01;
// TH0 = 0;
// TL0 = 0;
// TR0 = 1; //启动定时器0
// ET0 = 1; //允许定时器0中断
// EA = 1;
//}
void time_init()
{
EA = 1; //总中断允许
TMOD= 0x11; //8位自动重装模块
TH0 = 0;
TL0 = 0; //11.0592M晶振下占空比最大比值是256,输出100HZ
}
void main()
{
unsigned int time,distance;
EA = 1;
ET0 = 1;
ET1 = 1;
TMOD=0x11;
TH1 =0xff;
TL1 =0x9c;
servorTime = 0;
Trig = 0;
Echo = 0; //超声波脉冲
time_init();
while(1)
{
Trig = 1;
Delay_us (5);
Trig = 0;
while (Echo == 0);
TR0 = 1;
while (Echo);
TR0 = 0;
time = TH0*256+TL0;
distance = (int)(time*0.017); //计算路程 单位为cm
TH0 = 0;
TL0 = 0;
if (led1 == 0) //红外 检测到杂物
{
led = 0; //指示灯闪亮
delay(50);
led = 1;
delay(100);
control = 0; //舵机不转动
servorTime = 0;
TR1 = 0;
delay (200);
delay (200);
TR1 = 1;
delay (200);
delay (200);
if(led1 == 1)
led = 1;
}
else
{
if(distance>=40 && led1==1)
{
beep = 1;
control = 20; //使舵机向右摆动
servorTime =0;
TR1 = 1;
delay(200);
delay(200);
TR1 = 0;
delay(200);
delay(200);
}
if(distance<40 && led1==1) //如果距离小于40cm 蜂鸣器响
{
control = 5; //使舵机向左摆动
servorTime =0;
TR1 = 1;
delay(200);
delay(200);
TR1 = 0;
delay(200);
delay(200);
beep = 0;
delay (50);
beep = 1;
delay (2500);
}
}
}
}
void T1_int (void ) interrupt 3 //产生舵机所需要的脉冲
{
TH1 = 0xff;
TL1 = 0x9c;
servorTime++;
if(servorTime <= control)
servorControl = 1;
else
servorControl = 0;
if(servorTime >= 200)
servorTime=0;
}
|