0

I am making an Arduino project in which I have to control speed of DC motor with an ultrasonic sensor.

I have written an Arduino program to do this work but unfortunately my motor only rotates in forward and backward direction and when it comes in specific range like (50-95),(105-150) where I have to decrease the motor speed by 50 and 40 % then the motor only makes some noise - it does not rotate.

Components I am using:

  1. Arduino Uno
  2. L293D motor driver IC
  3. external 5 V/1.5 A power supply
  4. 9 volt motor

Code:

#define echoPin 2
#define trigPin 4
int enA = 9;
int in1 = 8;
int in2 = 7;
// defines variables
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
}
void loop() {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;

 Serial.print("Distance: ");
 Serial.print(distance);
 Serial.println(" cm");
 if (95<=distance && distance<=105)
 {
Serial.println("forwrd");
analogWrite(enA, 255);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
delay(2000);
 }
 else if(50<=distance && distance <=95){
 Serial.println("forward 40 %");
 digitalWrite(in1, HIGH);
 digitalWrite(in2, LOW);// forward
 analogWrite(enA,102);
 delay(2000);
 }
 else if(105<=distance && distance <=150){
 Serial.println("reverse 50%");
 digitalWrite(in1, LOW);
 digitalWrite(in2, HIGH);
 analogWrite(enA,127);
 delay(2000);
}
else if(10<= distance && distance<=50){
Serial.println("10-50 forwrd 40 %");
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);// forward
analogWrite(enA,102);
delay(2000);
}
else if(150<= distance && distance<=200){
 Serial.println("105-200 reverse 50%");
  digitalWrite(in1, LOW);
 digitalWrite(in2, HIGH);
 analogWrite(enA,127);
 delay(2000);
} 
}

Circuit diagram:

enter image description here

enter image description here

JRE
  • 67,678
  • 8
  • 104
  • 179
Muhammed
  • 11
  • 4
  • Any particular reason why you are using only a 5V supply for a 9V motor? – CalMachine Jun 26 '20 at 11:43
  • [Reasons not to use L293, L298 and SN754410 H-bridge drivers on a low voltage power supply](https://electronics.stackexchange.com/questions/108686/l293-l298-and-sn754410-h-bridge-drivers-on-low-voltage-power-supply). – Andy aka Jun 26 '20 at 11:58
  • 1
    No one will read this long code. Ask algorithm based thing, And use a 12 volt supply. L293D can't bear much load current. Keep that in mind too. – Sadat Rafi Jun 26 '20 at 14:54

0 Answers0