0

I wrote this sketch along with an HC - SR 04 Ultrasonic transducer and a DC motor. Whenever the HC-SR 04 reads any distance less than 15 cm, the motor stops, otherwise it keeps running.

The problem is whenever I upload the sketch, the motor runs for a short while and stops. Then when I open my serial monitor, the motor runs until an object crosses the 15 cm threshold and stops right after the limit is crossed. But when I again put the object outside of the 15 cm range, the motor should start running again, but it doesn't.

I am using a this motor driver and a simple DC motor(12V).
Here's the code-

int trigPin1 = A0;
int echoPin1 = A1;
int distance1 = 0;
int E1 = 10;
int brake1 = 7;


void setup() {
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(brake1, OUTPUT);
  pinMode (E1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  analogWrite(E1, 153);
  distance1 = getDistance(trigPin1, echoPin1);
  printDistance(1, distance1);
  delay(250);
  if(distance1 <=15){
    digitalWrite(brake1, HIGH);
  }
  else{
    analogWrite(E1, 153);
  }

}


int getDistance (int initPin, int echoPin) {
  digitalWrite(initPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(initPin, LOW);
  long pulseTime = pulseIn(echoPin, HIGH);
  int distance = pulseTime / 58.2;
  return distance;
}

void printDistance(int id, int dist) {

  Serial.print(id);
  if (dist >= 120 || dist <= 0 ) {
  Serial.println(" Out of range");
  }
  else{
   Serial.print("\t");
   Serial.print(dist);
   Serial.println(" cm");
}
}

What mistake am I doing? Moreover I am currently running it with one motor, I'll add another later on along with more sensors, so the motors are controlled by the left or right sensor. How do I make my code work with them?

Thanks...

0

It was too damn simple...

I just had to add a line inside the else block in the loop function.

digitalWrite(brake1, LOW);

This was happening because the first time the threshold limit was crossed the brake1 pin was left HIGH and was never set to LOW again, which caused a permanent brake in the motor.

I'm too damn stupid. But I still don't have any idea how will I use this code with multiple sensors and motors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.