Hello all I hope you are all doing well today. I am in quite a bit of a pickle. I am helping my boss do an Arduino workshop this thursday and we decided object avoiding robots would be neat. We got the parts in last week and I just now had time to put together one and I am having issues.
When I connect the sensor to the Arduino it works fine. It gives me clear reads and I have no issue. Now when I put the Motor Shield on the Arduino and then connect the sensor to the Arduino the sensor will work for a little bit then stop and then it works randomly when I fiddle with the ends of the cable. I swapped cables, sensors, Arduino, and the shield and I have not had any luck. I checked the pins on the motor shield that I am connecting the sensor to and they both directly to the Arduino. The 5v and GND rails I am connecting to go directly the the Arduino aswell. I have no idea why it is doing this so if you guys have any thoughts they would be greatly appreciated.
Here is my code.
#include <NewPing.h>
#include <AFMotor.h>
AF_DCMotor motor(1, MOTOR12_64KHZ); AF_DCMotor motor2(2, MOTOR12_64KHZ);
NewPing sonar(9,10);
long duration, inches;
long distance;
void setup() {
Serial.begin(9600);
Serial.println("Motor test!");
motor.setSpeed(200);
motor2.setSpeed(200);
}
void loop()
{
distance = pingMethod();
if(distance >=7){
motor.run(FORWARD);
motor2.run(FORWARD);
}
else{
motor.run(RELEASE);
motor2.run(RELEASE);
}
}
long pingMethod(){
duration = sonar.ping();
inches = microsecondsToInches(duration);
Serial.println(inches);
return inches;
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}