So I made this very basic program for an obstacle avoiding robot with one motor for each wheel, it's just supposed to turn one of them off if it detects something so it goes left, but I can't seem to be able to make the else part of the program work, either the motors stay off or they both keep going, the ultrasonic sensor is working just fine, as the console does show the correct values
const int pingPin = 7;
const int MotorA = 8;
const int MotorB = 9;
void setup() {
Serial.begin(9600);
}
void loop()
{
long duration, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
cm = microsecondsToCentimeters(duration);
pinMode(MotorA, OUTPUT);
pinMode(MotorB, OUTPUT);
if (cm > 40){
digitalWrite(MotorB, HIGH);
digitalWrite(MotorA, HIGH);
}else{
digitalWrite(MotorB, LOW);
digitalWrite(MotorA, LOW);
delay(100);
digitalWrite(MotorB, HIGH);
}
Serial.print(cm);
Serial.println();
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
and here are some improvements that I would suggest:
As suggested by PaulS put the pinMode() function calls in the setup function
Add a short delay after you switch on MotorB in the else block, the strange behavior shown by your robo is caused by the fact that MotorB s not getting enough time to move itself.
Hi Bill, no worries, I'd say a single tutorial could be conducted on program layout and ease of reading.
The auto format is great but still with experience, layout and commenting does eventually improve code reading and debugging.