In this tutorial we will take a look at using ultrasonic sensors, we are going to make a proximity alarm using a hc-sr04 with our Arduino board and a potentiometer to make an adjustable range proximity alarm…..
Click on video below for tutorial…
Parts List:
affiliate links
potentiometer
Bread board
jumper wires
Schematic:
ARDUINO Code:
#define trigPin 9
#define echoPin 10
long duration;
int distance;
int val;
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
val = (analogRead(A1));
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//distance = duration * 0.034 / 2; // cm
distance = duration * 0.0133 / 2; // in
Serial.println(distance);
val = map(val, 0, 1023, 6, 36);
Serial.println(val);
if (distance <= val)
{
tone(3, 500, 150);
delay(150);
tone(3, 300, 150);
delay(150);
}
//delay(500);
}