Hello,
I am trying to make an intruder-system. This system contains an ultrasonic sensor (HR-SR04) on top of a Servo (SG90) that continuously rotates. When the sensor detects an object within the range of 30 cm, a led turns on.
Both systems (sensor & servo) work great separate from each other. When i put them together, the servo rotates normal but the sensor only registers distance once every cycle.
I have tried solving this problem by using two different loops, but nothing seems to matter.
To sum up, i would like to have the servo and sensor operate at the same time.
Thank you in advance!
#include <NewPing.h>
#include <Servo.h>
#define trigPin 12
#define echoPin 13
#define MAX_DISTANCE 500
NewPing sonar(trigPin, echoPin, MAX_DISTANCE);
int led = 8;
int pos= 90;
int angle = 0;
Servo servo;
void loop() {
sonarr();
rotate();
}
void setup() {
// put your setup code here, to run once:
Serial.begin (115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
servo.attach(9);
servo.write(0);
}
void sonarr() {
// put your main code here, to run repeatedly:
int duration, distance, pos = 0, i;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
Serial.print(distance);
Serial.print(" cm ");
delay(1000);
if (distance >= 30) {
digitalWrite(led, HIGH);
delay(15);
}
else {
digitalWrite(led, LOW);
delay(15);
}
}
void rotate () {
for (angle = 0; angle < 180; angle++) {
servo.write(angle);
delay(15);
}
for (angle = 180; angle > 0; angle--) {
servo.write(angle);
delay(15); }
}