还好,这个模块有现成的库能够用:

https://github.com/bosgood/arduino-playground/tree/master/lib/HCSR04Ultrasonic


下面仅仅给出測试代码:

当距离小于20CM时蜂鸣器发出警报

#include "Ultrasonic.h"

#define TRIGGER_PIN  12
#define ECHO_PIN     13
#define BUF_PIN      7

Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);

void setup()
{
	Serial.begin(9600);
	pinMode(BUF_PIN, OUTPUT);
}

void loop()
{
	float cmMsec, inMsec;
	long microsec = ultrasonic.timing();

	cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);
	inMsec = ultrasonic.convert(microsec, Ultrasonic::IN);
	if(cmMsec < 20) {
		for(int i = 0; i < 80; i++) {
			digitalWrite(BUF_PIN, HIGH);
			delay(1);
			digitalWrite(BUF_PIN, LOW);
			delay(1);
		}
	}  
	Serial.print("MS: ");
	Serial.print(microsec);
	Serial.print(", CM: ");
	Serial.print(cmMsec);
	Serial.print(", IN: ");
	Serial.println(inMsec);
	delay(1000);
}


posted on 2017-08-08 08:23  yutingliuyl  阅读(505)  评论(0编辑  收藏  举报