Distancemeasurement-baf670f1/Distancemeasurement

61 lines
1.1 KiB
Text
Raw Normal View History

2015-08-27 07:33:37 +00:00
/*
A (neat) cheat way of getting the HC-SR04 distance sensor working on an Arduino Uno
put it in the end, with the GND aligned with the GND pin next to pin 13 and AREF
This example code is in the public domain.
*/
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
//int led = 13;
int echopin = 13;
int trigpin = 12;
int vcc = 11;
// the setup routine runs once when you press reset:
void setup() {
pinMode(echopin, INPUT);
pinMode(trigpin, OUTPUT);
pinMode(vcc, OUTPUT);
digitalWrite(vcc, HIGH);
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
long duration, distance;
digitalWrite(trigpin, LOW); // Added this line
delayMicroseconds(4); // Added this line
digitalWrite(trigpin, HIGH);
delayMicroseconds(20); // Added this line
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}