This commit is contained in:
commit
f7a1e99060
1 changed files with 61 additions and 0 deletions
61
Distancemeasurement
Normal file
61
Distancemeasurement
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
/*
|
||||
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);
|
||||
|
||||
}
|
||||
Loading…
Reference in a new issue