SR04库

《Arduino程序设计基础》中的示例程序。

github:

https://github.com/coloz/SR04-lib

 

ps:相关库由于有更新,可能用法和书上有差别,如遇问题,可以在Arduino中文社区提问

SR04.h:

#ifndef SR04_H
#define SR04_H

#include "Arduino.h"

class SR04 {
public:
	SR04(int TrigPin,int EchoPin);
	float GetDistance();

private:
	int Trig_pin;
	int Echo_pin;
	float distance;
};
#endif

SR04.cpp:

#include "Arduino.h"
#include "SR04.h"
 
SR04::SR04(int TP, int EP)
{
   pinMode(TP,OUTPUT);
   pinMode(EP,INPUT);
   Trig_pin=TP;
   Echo_pin=EP;
}
 
float SR04::GetDistance()
{
	digitalWrite(Trig_pin, LOW); 
	delayMicroseconds(2); 
	digitalWrite(Trig_pin, HIGH); 
	delayMicroseconds(10);
	digitalWrite(Trig_pin, LOW); 
	float distance = pulseIn(Echo_pin, HIGH) / 58.00;
	return distance;
}

Example:

#include <SR04.h>

SR04 ultrasonic = SR04(2,3);
void setup()
{
  Serial.begin(9600); 
}
void loop()
{
  float distance=ultrasonic.GetDistance();
  Serial.print(distance);
  Serial.print("cm");
  Serial.println(); 
}