Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HC-SR04 with power on and off to save power. Not working properly due to unknown reason. discussion here: http://forum.arduino.cc/index.php?topic=216079.0
const int trigPin = 6;
const int echoPin = 7;
const int powerPin = 5;
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(powerPin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop()
{
digitalWrite(powerPin, HIGH);
delay(10);
long duration = measureDistance();
long cm = microsecondsToCentimeters(duration);
Serial.println(duration);
Serial.println(cm);
Serial.println();
digitalWrite(powerPin, LOW);
if(cm < 30)
digitalWrite(ledPin, HIGH);
else
digitalWrite(ledPin, LOW);
delay(500); // this is not the lowePower sleep, first I am trying to make HC-SR04 work with power on and off
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 58;
}
long measureDistance(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
return(pulseIn(echoPin, HIGH));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.