I am making a basic 2WD robot using Arduino Uno with motor shield. I am getting no compile errors - but something in my logic flow is not working as expected.
Expected Operation:
- Ping sensor does distance check.
- If distance is less than 5cm.
- Turn both Channel A & B motors half-speed for 1 second.
- Stop motors.
- Take new distance reading ping, start again.
What however is happening, is that channel A works as expected, but channel B motor keeps running?? Where is my code / logic mistake?
Later date I will add to else statement to turn one wheel to change direction.
/*
HC-SR04 Ping distance sensor:
VCC to arduino 5v
GND to arduino GND
Echo to Arduino pin 7
Trig to Arduino pin 8
*/
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED
int maximumRange = 1000; // Maximum range needed
int minimumRange = 1; // Minimum range needed
long duration, distance; // Duration used to calculate distance
void setup() {
// put your setup code here, to run once:
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
pinMode(12, OUTPUT); /* Motor Channel A RIGHT SIDE*/
pinMode(9, OUTPUT); /* Motor Channel A */
pinMode(13, OUTPUT); /* Motor Channel B LEFT SIDE */
pinMode(8, OUTPUT);
}
void loop() {
/* Distance check begins */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
/* End distance check */
if (distance >= 5){
/* Distance great enough to provide room to move */
Serial.println("Move!");
digitalWrite(LEDPin, HIGH); /* LED show movement */
digitalWrite(12, LOW); /*move channel A motor half-speed */
digitalWrite(9, LOW);
analogWrite(3, 123);
digitalWrite(13, HIGH); /*move channel B motor half-speed */
digitalWrite(8, LOW);
analogWrite(11, 123);
delay(1000);
digitalWrite(9, HIGH);
digitalWrite(8, HIGH);
}
else {
/* Send the distance to the computer using Serial protocol, and
turn LED OFF to indicate successful reading. */
Serial.println(distance);
digitalWrite(LEDPin, LOW);
}
//Delay 50ms before next reading.
delay(500);
}
#definestatements. This way you could've easily spotted them having the same pin number. Some other points that might improve your code are:1.Try increasing the baudrateSerial.begin(115200)in both the code and your terminal (should make it a little quicker).`2.echoPin 7 // Echo Pinis just a too obvious comment. Try to use comments for a purpose. like//This pin receives the echo pulse3.maximumRangeshould be anunsigned intit makes no sense to have negative ranges (and you can have a higher max range with unsigned).