超声波传感器模块HC-SR04 是一种常用的测距传感器,可以测量静态距离,具有测量精度高、反应速度快等优点。通常可以配合arduino uno 也可以和其他的单片机开发板使用。
HC-SR04 有以下四个连接:
- VCC – 这是 5 伏正极电源。
- Trig——这是“触发”引脚,被驱动以发送超声波脉冲。
- ECHO– 这是在接收到反射信号时产生脉冲的引脚。脉冲的长度与检测到传输信号所需的时间成正比。
- GND – 这是接地引脚。
一般在arduino项目中需要占用单片机的两个引脚,一个连接trig用于发射超声波脉冲,另一个连接echo用于接受脉冲。但是根据其超声波模块原理知道发射脉冲和接受脉冲是两个互不干扰一前一后的过程,也就是说先发射后接收。所以我们可以将trig和echo连接在一个引脚之上,完成以前两个引脚才能完成的任务。这个方法对于引脚缺乏的开发板来说也很有用。
安装NewPing库
基本的测速草图:
#include <NewPing.h>
#define TRIGGER_PIN 10 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 10 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
Serial.print("Ping: ");
Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
Serial.println("cm");
}
不使用NewPing库的草图:
float duration; //变量duration 用来存储脉冲时间
float distance; //变量distance 用来存储距离
int srfPin = 4; //定义srfPin 引脚为4
void setup()
{
Serial.begin(9600);
}
void loop()
{
pinMode(srfPin, OUTPUT);
digitalWrite(srfPin, LOW);
delayMicroseconds(2);
digitalWrite(srfPin, HIGH);
delayMicroseconds(10);
digitalWrite(srfPin, LOW);
pinMode(srfPin, INPUT);
duration = pulseIn(srfPin, HIGH);
distance = duration/58; // 将脉冲时间转化为距离(单位:厘米)
Serial.println(distance); // 输出距离值
delay(50);
}
MIXLY(米思齐)中的使用方法: