This circuit is designed to control a DC motor using an L298N motor driver and an ultrasonic sensor, all managed by an Arduino UNO. The ultrasonic sensor detects clicks based on distance measurements, and the motor responds by moving forward on a single click and backward on a double click.
Arduino UNO
Ultrasonic Sensor
L298N DC Motor Driver
12V 7Ah Battery
DC Motor
Photodiode
/*
* This Arduino sketch controls a DC motor using an L298N motor driver and an
* ultrasonic sensor. A single click on the ultrasonic sensor triggers the motor
* to move forward, while a double click triggers the motor to move backward.
*/
// Pin definitions
const int triggerPin = 10;
const int echoPin = 9;
const int motorENAPin = 5;
const int motorIN1Pin = 3;
const int motorIN2Pin = 2;
// Variables for ultrasonic sensor
long duration;
int distance;
// Variables for click detection
unsigned long lastClickTime = 0;
int clickCount = 0;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize motor control pins
pinMode(motorENAPin, OUTPUT);
pinMode(motorIN1Pin, OUTPUT);
pinMode(motorIN2Pin, OUTPUT);
// Initialize ultrasonic sensor pins
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Measure distance using ultrasonic sensor
distance = measureDistance();
// Check for clicks
if (distance < 10) { // Assuming a click is detected when distance < 10 cm
unsigned long currentTime = millis();
if (currentTime - lastClickTime < 500) { // Double click detected
clickCount++;
} else { // Single click detected
clickCount = 1;
}
lastClickTime = currentTime;
}
// Perform actions based on click count
if (clickCount == 1) {
moveForward();
} else if (clickCount == 2) {
moveBackward();
clickCount = 0; // Reset click count after double click
}
delay(100); // Small delay to debounce
}
int measureDistance() {
// Clear the trigger pin
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Set the trigger pin HIGH for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// Read the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
int distance = duration * 0.034 / 2;
return distance;
}
void moveForward() {
digitalWrite(motorENAPin, HIGH);
digitalWrite(motorIN1Pin, HIGH);
digitalWrite(motorIN2Pin, LOW);
}
void moveBackward() {
digitalWrite(motorENAPin, HIGH);
digitalWrite(motorIN1Pin, LOW);
digitalWrite(motorIN2Pin, HIGH);
}
This code initializes the pins for the motor driver and ultrasonic sensor, measures the distance using the ultrasonic sensor, and controls the motor based on the detected clicks.