my robot, is a simple obstacle avoiding robot using the ping))) ultrasonic sensor. i have two continuously rotating servos that drive the robot. when i turn it on, and im holding the robot off the ground in air, it works perfectly fine. when i set it down on any surface it stops working.
#include <Servo.h>
Servo motorLeft;
Servo motorRight;
int ledPin = 13;
const int pingPin = 7;
void setup() {
motorLeft.attach(9);
motorRight.attach(10);
Serial.begin(9600);
}
void loop()
{
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
if(inches <= 10){
digitalWrite(ledPin, HIGH);
motorLeft.write(0);
motorRight.write(0);
}
else{
digitalWrite(ledPin, LOW);
motorLeft.write(180);
motorRight.write(0);
}
delay(300);
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
when in air it woks fine, and when i stick my hand 10 inches or closer it tries to turn, and when i move it away, it tries to go forward like its suppose to. but, when i set it on the ground, the ping))) flashes once, and gets stuck in its rotate loop.