- int TrigPin = 4;
- int EchoPin = 3;
- int buzzer = 5;
- int ledPin = 2;
- float distance;
- void beep() {
- digitalWrite(buzzer, HIGH); //发声音
- delay(distance*10);//延时1ms
- digitalWrite(buzzer, LOW); //不发声音
- delay(1);//延时ms
- }
- void led() {
- digitalWrite(ledPin, HIGH); //点亮小灯
- delay(distance*10); //延时1 秒
- digitalWrite(ledPin, LOW); //熄灭小灯
- delay(1); // 延时1 秒
- }
- void distan() {
- digitalWrite(TrigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(TrigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(TrigPin, LOW);
- // 检测脉冲宽度,并计算出距离
- distance = pulseIn(EchoPin, HIGH) / 58.00;
- delay(1);
- }
- void setup() {
- // put your setup code here, to run once:
- Serial.begin(9600);
- pinMode(TrigPin, OUTPUT);
- pinMode(EchoPin, INPUT);
- pinMode(buzzer, OUTPUT);
- pinMode(ledPin, OUTPUT);
- }
- void loop() {
- // put your main code here, to run repeatedly:
- distan();
- led();
- beep();
- }
- //该片段来自于http://www.codesnippet.cn/detail/2005201512620.html
来源: http://www.codesnippet.cn/detail/2005201512620.html