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);
}