I am having trouble with using distance sensor and servo motor at the same time. My project is a radar project. I have a servo motor sweeping around and on top of it I have distance sensor. When I compile and run this code, servo motor lags and does not sweep smoothly like it did without distance sensor. What can I do to avoid lag?
int main() {
while(1) {
runServo120();
}
}
long echo_duration() { //used for distance sensor
timer.reset();
trig = 0;
wait_us(2);
trig = 1;
wait_us(10);
trig = 0;
while(echo == 0);
timer.start();
while(echo == 1);
timer.stop();
return timer.read_us();
}
long distance(){ // used for distance sensor
long duration = echo_duration();
if(duration > 30000)
return -1;
long distacne_cm = duration /29 / 2 ;
return distacne_cm;
}
void runServo120(){ //sweeps 120 degree and calls distance() function
float angle = 0.00115;
for(int i = 0 ; i<50; i++){ //going forward
anglePin = 1;
wait(angle);
anglePin = 0;
wait(0.02-angle);
angle = angle + 0.000014;
if((int)distance() < 30){
myled = 0;
}else{
myled = 1;
}
}
angle = 0.00185;
for(int i = 0 ; i<50; i++){ //going backward
anglePin = 1;
wait(angle);
anglePin = 0;
wait(0.02-angle);
angle = angle - 0.000014;
if((int)distance() < 30){
myled = 0;
}else{
myled = 1;
}
}
}