i am making an animatronic rainbow stage beetle that will follow light. I am using to PR sensors for light, one ultrasonic sensors for obstacle detecting. the signal keeps dropping and I dont want to rely on AI to help fix my problem. Heres my code. HELP ME PLSSSSSSS.
#include <Servo.h>
Servo left;
Servo right;
int trigPin = 9;
int echoPin = 10;
int PRpin = A5;
int PRpin2 = A4;
long duration;
int distance;
int PRvalue;
int PRvalue2;
int baselineLight = 0; // for the photoresistors to take a baseline reading of the light.
int currentLight = 0;
int threshold = 50;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(PRpin, INPUT);
pinMode(PRpin2, INPUT);
Serial.begin(9600);
right.attach(A0);
left.attach(A2);
Serial.print("Calibrating, please wait.");
delay(3000);
baselineLight = analogRead(PRpin);
Serial.print("Baseline light level set:");
Serial.print (baselineLight);
}
void loop() {
digitalWrite(trigPin, LOW);// let it send out the signal
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn (echoPin, HIGH, 30000);
if (distance > 0) {
distance = (duration/2)/29.1;
Serial.print("Distance");
Serial.print(distance);
Serial.println(" cm");
} else {
distance = 401;
}
delay(100);
PRvalue = analogRead(PRpin);
PRvalue2 = analogRead(PRpin2);
Serial.print ("Current light:");
Serial.println(PRvalue);
Serial.print("Current light2:");
Serial.println(PRvalue2);
delay(1000);
if (distance <= 10){
right.write(90);
left.write(90);
}
else if (distance <=400 && distance >= 100){
right.write(0);
left.write(180);
}
else if (PRvalue > PRvalue2){
right.write(90);
left.write(180);
}
else if(PRvalue < PRvalue2){
right.write(0);
left.write(180);
}
delay(3000);
}