float distance ;
const int TrigPin = 4;
const int EchoPin = 5;
void setup()
{
Serial.begin(9600); //设置串口波特率
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
}
void loop()
{
distance = get_distance();
Serial.print(distance);
Serial.print("cm");
Serial.println();
delay(1000);
}
float get_distance()//获取距离 cm
{
// 产生一个10us的高脉冲去触发TrigPin
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
distance = pulseIn(EchoPin, HIGH) / 58.00;
return distance > 510 ? 0:distance;
}