How sensor works:-
The sensor sends ultrasound(Through the 'Transmitter(T)'). When any object comes in between of its path, the rays get reflected and are received by the 'Receiver(R)'.
Velocity of sound is known, and the time is started when the rays are sent and stopped when the rays are received. Then with the formula, the distance is found.
In a nutshell:-
Interface:-
Name of the pins are written on the Sensor(Just above pins).
Vcc ---> 5v (3.3v will not work)
GND -----> GND
TRIG ------>9
ECHO ------>10
Trig is for the transmitter, Echo is for the receiver.
Code:-
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distanceCm;
Defining pins and declaring variables
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
Void setup and starting serial at baudrate 9600 and defining pinmodes of trig and echo pins.
void loop() {
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;
if(distanceCm>30){
distanceCm=0;
}
delay(50);
}
Creating a pulse to get duration and then converting it into distance(CM) by using formula, and also if distance is greater than 30 show it zero.
For using OLED to display result, please read:-
https://www.hackster.io/jasrajdevs/arduino-distance-calculator-2f793c
Comments
Please log in or sign up to comment.