Skip to content

Instantly share code, notes, and snippets.

@mhmoodlan
Created October 16, 2020 21:10
Show Gist options
  • Save mhmoodlan/a0e5d27f112345cac1679c6ef2f0eed7 to your computer and use it in GitHub Desktop.
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.
#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