I've written a code based off a test for the ping sensor using a led, I replaced the led with a dc motor command, but I'm having trouble with getting the ping to go enough times per second to get the data to tell it to stop. Basically I've built a little car with an Arduino UNO board, Arduino motor shield and a parallax ping sensor, the entire system works to move an egg from a point straight toward a wall stopping at 3 cm away from the wall. My problem is that the car will run and if the sensor happens to sense at the correct time it will stop but if its at an interval between sensing the car will run into the wall. Any ideas on how to decrease the interval, heres my frankenstein code.
#define fP 7 //Pin the ping sensor is connected to
void setup()
{
pinMode(12, OUTPUT);
}
void loop()
{
if (ping() > 50)
{
digitalWrite(12, HIGH); // set the LED on
analogWrite(3, 145);
}
else
{
analogWrite(3, 0); // set the LED off
}
}
int ping() //Get CM to obstacle in front of the sensor
{
long duration;
pinMode(fP, OUTPUT);
digitalWrite(fP, LOW);
delayMicroseconds(2);
digitalWrite(fP, HIGH);
delayMicroseconds(15);
digitalWrite(fP, LOW);
delayMicroseconds(20);
pinMode(fP, INPUT);
duration = pulseIn(fP, HIGH);
return duration / 29.0 / 2.0;
}