So this is my code and I use micro servo motor 9g:
#include <Servo.h>
const int Serv1 = 8;
const int Serv2 = 9;
const int Trigger = 6;
const int Echo = 7;
const int Light = 10;
const int LED1 = 11;
const int LED2 = 12;
const int LED3 = 13;
long duration;
int distance;
int detect;
int pos = 0;
int pos2 = 0;
Servo Servo1, Servo2;
void setup() {
// put your setup code here, to run once:
Servo1.attach(Serv1);
Servo2.attach(Serv2);
pinMode(Trigger, OUTPUT);
pinMode(Echo, INPUT);
Serial.begin(9600);
pinMode(Light, INPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(Trigger, LOW);
digitalWrite(Trigger, HIGH);
digitalWrite(Trigger, LOW);
duration = pulseIn(Echo, HIGH);
distance = duration*0.034/2;
Serial.print("Distance: ");
Serial.println(distance);
detect = digitalRead(Light);
Serial.print("Light: ");
Serial.println(detect);
if (distance < 10 && detect == 0) { //Ultrasonic sensor
digitalWrite(LED1, HIGH);
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
Servo1.write(pos); // tell servo to go to position in variable ‘pos’
delay(5); // waits 15ms for the servo to reach the position
}
}
else {
digitalWrite(LED1, LOW);
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
Servo1.write(pos); // tell servo to go to position in variable ‘pos’
delay(5); // waits 15ms for the servo to reach the position
}
}
if (distance > 10 && detect == 1) { // LDR Sensor
digitalWrite(LED2, HIGH);
for (pos2 = 0; pos2 <= 90; pos2 += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
Servo2.write(pos2); // tell servo to go to position in variable ‘pos’
delay(5); // waits 15ms for the servo to reach the position
}
}
else {
digitalWrite(LED2, LOW);
for (pos2 = 90; pos2 >= 0; pos2 -= 1) { // goes from 180 degrees to 0 degrees
Servo2.write(pos2); // tell servo to go to position in variable ‘pos’
delay(5); // waits 15ms for the servo to reach the position
}
}
if (distance < 10 && detect == 1) {
digitalWrite(LED3, HIGH);
}
else {
digitalWrite(LED3, LOW);
}
}
the problem is even when the sensor didn’t detect anything the motors acts out on its own
and when it actually detects then goes to its position then I move away, it will stay in it’s position it won’t go back to it’s original position right away or it won’t move at all