const int TrigPin = 4;
const int EchoPin = 3;
const int BELLPin = 11;
int AudioVoice = 678; //音频范围为0~1023
boolean CtrlFlag = false;
float distance;
void setup()
{
Serial.begin(115200);
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
pinMode(BELLPin, OUTPUT);
noTone(BELLPin);
}
void loop()
{
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
distance = pulseIn(EchoPin, HIGH) / 58.0;
Serial.println(distance);
if (distance < 50)
{
CtrlFlag = true;
tone(BELLPin, AudioVoice);
}
else
{
CtrlFlag = false;
noTone(BELLPin);
}
}