So I want to make a code that will pan a ping sensor 180 degrees while taking distance readings at constant intervals. Right now, my code makes the servo move very choppily and the ping takes readings at different intervals. Any suggestions?
#include <Servo.h>
Servo myservo;
int pos = 0;
int pingPin = 2;
long duration, distance;
int previousMillis = 0;
int interval = 100;
void setup()
{
Serial.begin(9600);
myservo.attach(9);
}
void loop()
{
for(pos = 0; pos < 160; pos += 2)
{
myservo.write(pos);
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
distance = duration / 29 / 2;
Serial.print("PING = ");
Serial.println(distance);
delay(25);
}
for(pos = 160; pos>=1; pos -= 2)
{
myservo.write(pos);
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
distance = duration / 29 / 2;
Serial.print("PING = ");
Serial.println(distance);
delay(25);
}
}