Controlling a DC motor with Ultrasonic sensor

Hi guys,

I’m new to this and still there’s still so much that I can learn. What I’m trying to do is I’m trying to control a 5v DC motor with an ultrasonic sensor. Basically what I want is that the distance determines the speed of the motor, whereas an object that’s further away speeds up the motor, and when the object is close it’ll slow down the motor. So far no luck, even though I know for a fact that the sensors are working because of the serial print thingy

So far I have this: (I’m a big noob and don’t know if this is correct) and any help would be highly appreciated

#define trigPin 13
#define echoPin 12
#define motorPin 8

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motorPin, INPUT);
}

void loop () {
int duration, distance;
digitalWrite (trigPin, HIGH);
delayMicroseconds (1000);
digitalWrite (trigPin, LOW);
duration = pulseIn (echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 20) { // Distance from sensor
digitalWrite (motorPin, HIGH); // When in range, motor should start high
}
else {
digitalWrite(motorPin, LOW);
}
if (distance > 20) { // Distance from sensor
Serial.println(“Out of range”);
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}

You can't drive a motor direct from an arduino pin you need a driver, like a transistor.

To control the speed feed the motor with a PWM signal, you get it from an analogWrite function, this only works with certain pins, see your arduino model for which.

For information on PWM see:- http://www.thebox.myzen.co.uk/Tutorial/PWM.html

Grumpy_Mike: You can't drive a motor direct from an arduino pin you need a driver, like a transistor.

To control the speed feed the motor with a PWM signal, you get it from an analogWrite function, this only works with certain pins, see your arduino model for which.

For information on PWM see:- http://www.thebox.myzen.co.uk/Tutorial/PWM.html

Its alright, the code is safe due to:

  pinMode(motorPin, INPUT);

:)