Hi everyone,
I am still a beginner but I was trying out a bigger project when for some reason I ran into a super weird problem that I have not encountered before; the code within my Void setup() is repeating. As you can see down in my program I had a for loop in the setup and I originally thought that was the problem but I took it out and it continued to do the same thing. I know it is repeating because my servo repeats that process and I get a "setup" message in the serial monitor (which I had programmed into the setup part). Here is the code, and the basic idea of the project is to make a monitor that scans back and forth to detect distance using sonar, and then capture those distances on an array as to know when something is in the "room." I need an "original" scan to get all of the distances and store them into an array before it continues to scan back and forth which is why the for loop is in the setup (). Either I missed something super simple or this is way above me, but please help. Thank you in advance!
#include <Servo.h>;
Servo radarTurner;
const int degreeJump = 3;
const int triggerPin = 3;
const int echoPin = 5;
const int startAngle = 70;
const int endAngle = 120;
int distanceArray[((endAngle - startAngle) / degreeJump)];
int returnDistance(int servoAngle) {
radarTurner.write(servoAngle);
delay(400);
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(5);
digitalWrite(triggerPin, LOW);
int duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.034/2;
Serial.println(distance);
return distance;
}
void setup() {
radarTurner.attach(9);
Serial.begin(9600);
pinMode(6, OUTPUT);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
radarTurner.write(startAngle);
for(int i = startAngle; i <= endAngle; i += degreeJump) {
distanceArray[((i - startAngle) / degreeJump)] = returnDistance(i);
//Serial.println(distanceArray[((i - startAngle) / degreeJump)]);
}
}
void loop() {
const int bufferZone = 5;
for(int i = endAngle; i >= startAngle; i -= degreeJump) {
distanceArray[((i - startAngle) / degreeJump)] = returnDistance(i);
//Serial.write(distanceArray[((i - startAngle) / degreeJump)]);
if(returnDistance(i) < (distanceArray[((i - startAngle) / degreeJump)] - bufferZone)){
digitalWrite(6, HIGH);
delay(6000);
digitalWrite(6, LOW);
//break;
}
}
for(int i = startAngle; i <= endAngle; i -= degreeJump) {
distanceArray[((i - startAngle) / degreeJump)] = returnDistance(i);
//Serial.write(distanceArray[((i - startAngle) / degreeJump)]);
if(returnDistance(i) < (distanceArray[((i - startAngle) / degreeJump)] - bufferZone)){
digitalWrite(6, HIGH);
delay(6000);
digitalWrite(6, LOW);
//break;
}
}
}