Professional Documents
Culture Documents
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);
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
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.