Created
October 16, 2020 21:10
-
-
Save mhmoodlan/a0e5d27f112345cac1679c6ef2f0eed7 to your computer and use it in GitHub Desktop.
Arduino script to measure average distance using HC-SR04 ultrasonic sensor and buzzing as the distance gets less than a threshold (10cm) with increasing frequency as the distance gets shorter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define echoPin 7 | |
#define trigPin 8 | |
long duration; | |
long distance; | |
int n = 0; | |
double accumulator = 0.0; | |
void setup() { | |
Serial.begin(9600); | |
pinMode(echoPin, INPUT); | |
pinMode(trigPin, OUTPUT); | |
} | |
void loop() { | |
digitalWrite(trigPin, LOW); | |
delayMicroseconds(2); | |
digitalWrite(trigPin, HIGH); | |
delayMicroseconds(10); | |
digitalWrite(trigPin, LOW); | |
duration = pulseIn(echoPin, HIGH); | |
distance = duration /58.2; | |
if(distance < 10) { | |
tone(11, (1.0/(distance*10.))*30000); | |
delay((distance*1.0/2.0)*100); | |
noTone(11); | |
} | |
n+=1; | |
accumulator += distance; | |
Serial.println(accumulator/n); | |
//Serial.println(distance); | |
delay(50); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment