Ultrasonic sensors are widely used for distance measurement applications. In this blog, we will break down a simple Arduino code that measures distance using an ultrasonic sensor. The code makes use of two pins: one for sending the trigger signal and one for receiving the echo signal. Here’s how each part of the code works:
Pin Definitions
int trig = 3;
int echo = 3;
int distance;
int tim;
int trig = 3; This line defines the pin `3` as the trigger pin. The trigger pin is responsible for sending out an ultrasonic pulse.
int echo = 2;This line defines the pin `2` as the echo pin. The echo pin is used to receive the reflected ultrasonic pulse.
int distance; : This variable will store the calculated distance.
int tim; : This variable will store the time duration of the echo signal.
Setup Function
void setup() {
Serial.begin(9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
- Serial.begin(9600);: Initializes the serial communication at a baud rate of 9600 bps. This allows you to send data to the serial monitor for debugging or logging purposes.
- pinMode(trig, OUTPUT);: Sets the `trig` pin as an output. This pin will send the ultrasonic pulse.
- pinMode(echo, INPUT);: Sets the `echo` pin as an input. This pin will read the reflected pulse.
Loop Function
void loop() {
digitalWrite(12, LOW);
digitalWrite(trig, HIGH);
delay(1000);
digitalWrite(trig, LOW);
tim = pulseIn(echo, HIGH);
distance = (tim * 0.034) / 2;
Serial.print("distance: ");
Serial.println(distance);
}
- digitalWrite(12, LOW); : (This line is likely a mistake or unnecessary since pin 12 is not defined or used elsewhere in the code. It can be removed.)
- digitalWrite(trig, HIGH); : Sends a high signal (5V) to the trigger pin, initiating an ultrasonic burst.
- delay(1000); : Waits for 1 second (1000 milliseconds) to allow the pulse to travel and reflect back.
- digitalWrite(trig, LOW); : Stops the trigger signal after the pulse is sent.
- tim = pulseIn(echo, HIGH); : Measures the time duration for which the echo pin receives the reflected signal. This time is stored in the variable `tim`.
- distance = (tim * 0.034) / 2; : Calculates the distance by converting the time duration to distance. The speed of sound is approximately 0.034 cm/μs, and dividing by 2 accounts for the pulse travelling to the object and back.
- Serial.print("distance: "); : Prints the text "distance: " to the serial monitor.
-Serial.println(distance); : Prints the calculated distance value to the serial monitor followed by a new line.
Conclusion
This code snippet provides a simple way to measure distance using an ultrasonic sensor with an Arduino. It initializes the sensor pins, sends an ultrasonic pulse, measures the time for the echo to return, and calculates the distance based on this time.
For the complete code and more details, you can refer to the full code on Click here
Comments
Post a Comment