-
超声波的Echa接口P10,Trig口接P11。舵机的信号线接入P12
-
振动传感器的接入P13,蜂鸣器的接入P14。
-
当按键按下,或者检测到振动,或者超声波测得距离小于5cm是,舵机旋转180度,2s后复原。此时蜂鸣器响2s。
-
其中舵机使用的是SG90,超声波模块使用的是HC-SR04,有源蜂鸣器使用的是低电平触发,振动传感器为SW-1801P
#include <STC89C5xRC.H>
#include "intrins.h"
sbit echa=P1^0;
sbit trig=P1^1;
sbit pwm=P1^2;
sbit vibrate=P1^3;
sbit been=P1^4;
sbit keyOne=P2^1;
int count_f=1;
unsigned int time;
unsigned int distance;
int count_1;
int SGTemp=0;
void Delay2000ms()
{
unsigned char i, j, k;
_nop_();
i = 15;
j = 2;
k = 235;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void Delay10ms()
{
unsigned char i, j;
i = 18;
j = 235;
do
{
while (--j);
} while (--i);
}
void Delay10us()
{
unsigned char i;
i = 2;
while (--i);
}
void Timer0Init(void)
{
AUXR &= 0x7F;
TMOD &= 0xF0;
TMOD |= 0x01;
TL0 = 0x33;
TH0 = 0xFE;
TF0 = 0;
TR0 = 1;
ET0=1;
EA=1;
}
void timer0Service() interrupt 1
{
TL0 = 0x33;
TH0 = 0xFE;
count_1++;
if(count_1<=count_f)
{
pwm=1;
}
else
{
pwm=0;
}
if(count_1>40)
{
count_1=0;
}
}
void Timer1Init(void)
{
AUXR &= 0xBF;
TMOD &= 0x0F;
TMOD |= 0x10;
TL1 = 0x00;
TH1 = 0x00;
TF1 = 0;
TR1 = 0;
ET1=1;
EA=1;
}
void startHC()
{
trig=0;
trig=1;
Delay10us();
trig=0;
}
void getDistance()
{
startHC();
while(echa==0);
TR1=1;
while(echa==1);
TR1=0;
if(TF1==0)
{
time=TH1;
time=(time<<8)|TL1;
time=time*1.085;
distance=time*0.0017;
}
else
{
TF1=0;
distance=999;
}
TH1=TL1=0x00;
}
void keyBoard()
{
if(keyOne==0)
{
Delay10ms();
if(keyOne==0)
{
SGTemp=1;
}
while(!keyOne);
}
}
void distanceWork()
{
if(distance<=5)
{
SGTemp=1;
}
}
void vibrateWork()
{
if(vibrate==0)
{
SGTemp=1;
}
}
void steeringWork()
{
if(SGTemp==1)
{
been=0;
SGTemp=0;
count_f=5;
Delay2000ms();
been=1;
}
if(SGTemp==0)
{
count_f=1;
}
}
void main()
{
Timer1Init();
Timer0Init();
while(1)
{
keyBoard();
getDistance();
steeringWork();
vibrateWork();
distanceWork();
}
}