If I rem the line a[x]=cm in the Ping function everything works as advertised.
I have the Mega2560 plugged into a 9Vdc (6 x 1.5Vdc AA) battery pack and USB. I have tried a 12Vdc battery with no change.
I also tried moving the servo to pin 10 with no change
Any help would be greatly appreciated.
Cheers!
#include <Servo.h>
Servo myservo;
int pos;
int lim1=60;
int lim2=120;
int wait=50;
const int pingPin = 38;
long duration;
long cm;
long a[3];
int res=1;
void setup()
{
myservo.attach(9);
Serial.begin(9600);
}
void loop()
{
for(pos = lim1; pos < lim2; pos +=1)
{
servoScan();
Ping();
Report();
}
for(pos = lim2; pos>lim1; pos-=1)
{
servoScan();
Ping();
Report();
}
}
long microsecondsToCentimeters(long microseconds){
return microseconds / 29 / 2;
}
void servoScan(){
myservo.write(pos);
delay(wait);
// Serial.println(pos);
}
void Ping(){
for (int x = 0; x <= 3 ; x++) {
delay(wait);
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);
a[x]=cm; // this makes the servo stop moving
}
}
void Report(){
Serial.print(pos);
Serial.print(" degrees ");
Serial.print(cm);
Serial.println(" cm");
delay(wait);
}