You are on page 1of 2

code of Arduino nano for obstacle detection using ultrasonic sensor HC- SR04 and

arduino nano and led light

ChatGPT
Certainly! Here's an example code for obstacle detection using an Arduino Nano, an
HC-SR04 ultrasonic sensor, and an LED light:

cpp
Copy code
// Define the pin connections
const int trigPin = 2;
const int echoPin = 3;
const int ledPin = 4;

// Variables
long duration;
int distance;

void setup() {
// Initialize serial communication
Serial.begin(9600);

// Define pin modes


pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}

void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Activate the trigger pulse


digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Measure the echo pulse duration


duration = pulseIn(echoPin, HIGH);

// Calculate the distance


distance = duration * 0.034 / 2;

// Print the distance on the serial monitor


Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

// Check if an obstacle is within 10 cm


if (distance <= 10) {
// Turn on the LED light
digitalWrite(ledPin, HIGH);
} else {
// Turn off the LED light
digitalWrite(ledPin, LOW);
}

// Delay before the next measurement


delay(100);
}
Make sure to connect the HC-SR04 ultrasonic sensor's VCC pin to the 5V pin on the
Arduino Nano, the GND pin to the GND pin on the Arduino Nano, the Trig pin to pin
2, and the Echo pin to pin 3. Additionally, connect an LED with a suitable current-
limiting resistor to pin 4.

This code continuously measures the distance using the ultrasonic sensor and prints
it on the serial monitor. If an obstacle is detected within 10 cm, it turns on the
LED light. When there is no obstacle within the specified range, the LED light
remains off.

Remember to adjust the distance threshold and the pin assignments according to your
setup.

You might also like