I just started using Arduino Uno, I can't get the ultrasonic to work ,with motor controller board, the output value is always zero.
Just to make sure I'm talking about the correct stuff: I used this guide to try to make it work (look at the picture how did I connect the parts).
And this is my code:
#define trigPin A4//Attach Trig to port 8
#define echoPin A5//Attach Echo to port 7
#include <AFMotor.h>
//SMARS Demo 2 with Line sensor
AF_DCMotor R_motor(2); // defines Right motor pin
AF_DCMotor L_motor(1); // defines Left motor pin
int lmotorpin1 = 3;
int lmotorpin2 = 5;
int rmotorpin1 = 6;
int rmotorpin2 = 9;
int distancecm = 0;
//const int trigPin = 18;
//const int echoPin = 19;
// defines variables
long duration;
int distance;
void setup() {
Serial.begin(9600); // sets up Serial library at 9600 bps
//changes the following values to make the robot drive as straight as possible
L_motor.setSpeed(200); // sets L motor speed
R_motor.setSpeed(140); // sets R motor speed
R_motor.run(RELEASE); //turns L motor on
L_motor.run(RELEASE); //turns R motor on
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
Serial.println(trigPin);
Serial.println(echoPin);
distancecm = mdistance();
if (distance < 5) {
L_motor.run(BACKWARD); //moves motor L Forward
R_motor.run(FORWARD); //moves motor L Forward
// delay(1000);
// L_motor.run(FORWARD); //moves motor L Forward
// R_motor.run(FORWARD); //moves motor L Forward
// delay(1000);
}
else {
L_motor.run(FORWARD); //moves motor L Forward
R_motor.run(FORWARD); //moves motor L Forward
}
}
int mdistance()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
Serial.print("Duration: ");
Serial.println(duration);
// Calculating the distance
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
As you can see I tried different pin numbers but it always 0 ....
what do you think can be wrong?
The motors work. Motor Controller: KEYES L293D Motor Control Shield Sensor: Ultrasonic Ranger V2.0
the ranger does not work with the motor controller, but it works without the motor controller
..... is that what is happening?