7.Ultrasonic DC motor Driver
Ultrasonic DC motor Driver
Materials Needed:
- Arduino board
- Ultrasonic sensor (e.g., HC-SR04)
- DC motor (or servo motor)
- Motor driver (e.g., L298N for a DC motor)
- External power supply (depending on the motor requirements)
- Jumper wires
- Breadboard (optional)
Connections for DC Motor:
Ultrasonic Sensor to Arduino:
- TRIG pin → Pin 9
- ECHO pin → Pin 10
- VCC pin → 5V
- GND pin → GND
Motor Driver to Arduino (using L298N as an example):
- Connect IN1 on the motor driver to Pin 6 on the Arduino.
- Connect IN2 on the motor driver to Pin 7 on the Arduino.
- Connect the motor terminals to OUT1 and OUT2 of the motor driver.
- Connect 12V external power supply to the motor driver.
- Connect GND from the motor driver to Arduino GND.
- Enable pin (ENB) on the motor driver to 5V.
Procedure:
Connect the Ultrasonic Sensor and Motor:
- Use jumper wires to connect the ultrasonic sensor, motor driver, and motor as described above.
Write the Arduino Code (DC Motor Example):
- Copy and paste the following code into the Arduino IDE:
C++ Code
const int trigPin = 9;
const int echoPin = 10;
const int motorPin1 = 6;
const int motorPin2 = 7;
int thresholdDistance = 20; // Set the distance threshold in centimeters
void setup() {
Serial.begin(9600); // Start the serial communication at 9600 baud rate
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
}
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");
// Turn on the motor if the object is closer than the threshold distance
if (distance <= thresholdDistance) {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW); // Motor moves in one direction
} else {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW); // Turn off the motor
}
delay(500); // Wait for a short while before the next measurement
}
Comments
Post a Comment