This circuit is designed to control a motor driver, an ultrasonic sensor, and a servo motor using an Arduino UNO. The ultrasonic sensor measures distance, and based on the distance, an LED blinks a specified number of times. The results are also printed to the serial monitor.
Arduino UNO
Motor with reducer
L298N DC motor driver
HC-SR04 Ultrasonic Sensor
Micro servo 9G
7.4v Battery
/*
* This Arduino sketch controls a motor driver, ultrasonic sensor, and a servo.
* The ultrasonic sensor measures distance, and based on the distance, the LED
* blinks a specified number of times. The results are also printed to the
* serial monitor.
*/
#include <Servo.h>
// Pin definitions
const int trigPin = 8;
const int echoPin = 9;
const int ledPin = 13;
const int servoPin = 3;
const int motorIn1 = 7;
const int motorIn2 = 6;
const int motorIn3 = 5;
const int motorIn4 = 4;
Servo myServo;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(motorIn1, OUTPUT);
pinMode(motorIn2, OUTPUT);
pinMode(motorIn3, OUTPUT);
pinMode(motorIn4, OUTPUT);
// Attach the servo
myServo.attach(servoPin);
}
void loop() {
// Measure distance
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
// Print distance to serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Blink LED based on distance
if (distance >= 3 && distance <= 5) {
blinkLED(5);
} else if (distance >= 10 && distance <= 20) {
blinkLED(10);
}
// Small delay before next measurement
delay(500);
}
void blinkLED(int times) {
for (int i = 0; i < times; i++) {
digitalWrite(ledPin, HIGH);
delay(250);
digitalWrite(ledPin, LOW);
delay(250);
}
}
This code initializes the pins for the ultrasonic sensor, motor driver, and servo motor. It measures the distance using the ultrasonic sensor and blinks an LED based on the measured distance. The results are printed to the serial monitor.