const int trigPin = 2; // Trigger pin of HC-SR04 const int echoPin = 3; // Echo pin of HC-SR04 const int motorPin1 = 8; // Input 1 of L293D const int motorPin2 = 11; // Input 2 of L293D const int enablePin = 12; // Enable pin of L293D void setup() { // For the ultrasonic sensor pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); // For the gear motor pinMode(motorPin1, OUTPUT); pinMode(motorPin2, OUTPUT); pinMode(enablePin, OUTPUT); // Initialize serial communication at 9600 Serial.begin(9600); } void loop() { // Measure distance long duration, distance; digitalWrite(trigPin, LOW); digitalWrite(trigPin, HIGH); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); // Read the echo pulse distance = duration * 0.034 / 2; // Convert distance to centimeters // Print the distance for debugging Serial.print("Distance: "); Serial.println(distance); // If an object is within 20 cm, turn on the motor if (distance > 0 && distance <= 20) { digitalWrite(motorPin1, HIGH); // Set motor pin 1 to high digitalWrite(motorPin2, LOW); // Set motor pin 2 to low analogWrite(enablePin, 155); // Set the speed of the gear motor delay(20); // Set how long the gear motor runs before turning off analogWrite(enablePin, 0); // Turn off the gear motor delay(2); // Set how long until the gear motor turns on again } // If there is no object within 20 cm from the sensor, turn everything off else{ digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); analogWrite(enablePin, 0); } delay(100); // Delay for 100 seconds }