Ultrasonic Sensor not working with Motors

I'm trying to use an Ultrasonic sensor to stop 2 DC motors within a specific distance of an object. I've tested the sensor with an LED which works fine, and the motors run without the sensor. I'm using a Transistor & Diode to Drive the motor. I can see the sensor working in the Serial Monitor, it just doesn't affect the motors.
Here's my code:

const int TRIG_PIN = 11; // Arduino pin connected to Ultrasonic Sensor's TRIG pin
const int ECHO_PIN = 12; // Arduino pin connected to Ultrasonic Sensor's ECHO pin
const int MOTOR_PIN  = 3; // Arduino pin connected to Motor
const int DISTANCE_THRESHOLD = 10; // centimeters


float duration_us, distance_cm;

void setup() {
  Serial.begin (9600);      
  pinMode(TRIG_PIN, OUTPUT); 
  pinMode(ECHO_PIN, INPUT);  
  pinMode(MOTOR_PIN, OUTPUT);  
}

void loop() {
 
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  
  duration_us = pulseIn(ECHO_PIN, HIGH);
 
  distance_cm = 0.017 * duration_us;

  if(distance_cm > DISTANCE_THRESHOLD)
    digitalWrite(LED_PIN, HIGH); // turn on LED
  else
    digitalWrite(LED_PIN, LOW);  // turn off LED


  Serial.print("distance: ");
  Serial.print(distance_cm);
  Serial.println(" cm");

  delay(500);
}


Thanks for the help

Maybe because you never digitalWrite to the MOTOR_PIN?

1 Like

Even worse, you write to 'LED_PIN', a name that is not defined. The sketch won't compile.

How does the diode drive the motor? If it is for flyback that's good. If it drives the motor please post a schematic of the circuit.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.