1.Ultrasonic Basic project
Ultrasonic Basic project
Materials Needed:
- Arduino board
- Ultrasonic sensor (e.g., HC-SR04)
- Jumper wires
Connections:
- Ultrasonic Sensor to Arduino:
- TRIG pin → Pin 9
- ECHO pin → Pin 10
- VCC pin → 5V
- GND pin → GND
Procedure:
Connect the Ultrasonic Sensor:
- Use the jumper wires to connect the ultrasonic sensor pins as mentioned above.
- Ensure proper power and ground connections for the sensor to work correctly.
Write the Arduino Code:
- Copy and paste the following code into the Arduino IDE:
- C++ Code
const int trigPin = 9;const int echoPin = 10;
void setup() { Serial.begin(9600); // Start the serial communication at 9600 baud rate pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);}
void loop() { long duration; int distance;
// Send a 10us pulse to trigger the sensor digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters distance = duration * 0.034 / 2;
// Print the distance to the serial monitor Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm");
delay(500); // Wait for a short while before the next measurement}
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600); // Start the serial communication at 9600 baud rate
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration;
int distance;
// Send a 10us pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Wait for a short while before the next measurement
}
Comments
Post a Comment