Variable not setting in while loop.

I’m trying to get a servo to sweep a photoresistor 180 degrees when bttn1 is pressed. Upon finding the highest light intensity with the photoresistor, apply the current pos to maxPos. When btt2 is pressed set servo to maxPos. For some reason maxPos always returns 0… any help would be greatly appreciated.

#include <LiquidCrystal.h>
#include <Servo.h>


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int bttnPin1 = 8;
const int bttnPin2 = 7;
int lght = 0;
long maxPos = 0;
int lghtMax = 0;
int pos = 0;
int bttn1 = 0;
int bttn2 = 0;
Servo myservo;

void setup() {
  
  myservo.attach(9);
  pinMode(bttnPin1, INPUT);
  pinMode(bttnPin2, INPUT);
  
  lcd.begin(16, 2);  
  lcd.print("Max Light: "); 
  lcd.setCursor(0, 1);
  lcd.print("Max Position: "); 
  myservo.write(pos);
}

void loop() {
  
  delay(15);
  bttn1 = digitalRead(bttnPin1);
  bttn2 = digitalRead(bttnPin2);
  lght = analogRead(0);
  
  if(bttn1 == HIGH) {
    while(pos < 180) {
      
      if(lghtMax < lght) {
        lghtMax = lght;
        maxPos = pos;
      }
      myservo.write(pos);
      delay(15);
      pos++;      
    }
  }
  if(bttn2 == HIGH) {
    myservo.write(maxPos);
    lcd.clear();
    pos = 0;
    lghtMax = 000;
  }

  lcd.setCursor(0, 0);
  lcd.print("Max Light: "); 
  lcd.setCursor(0, 1);
  lcd.print("Max Position: ");
  lcd.setCursor(14, 1);
  lcd.print(maxPos);
  lcd.setCursor(12, 0);
  lcd.print(lghtMax);
   
  

  
  
}

sketch_may06a.ino (1.09 KB)

(deleted)

lghtMax returns the correct value. I've tried using myservo.read() instead of maxPos = pos; returns the same thing 0. Which is strange b/c the servo is moving. meaning pos has a value > 0.

Like spycatcher2K says, you need to bring the analogRead() into the while() loop sweep

if(bttn1 == HIGH) {
  while(pos < 180) {
    
    lght = analogRead(0);

    if(lghtMax < lght) {
      lghtMax = lght;
      maxPos = pos;
    }
    myservo.write(pos);
    delay(15);
    pos++;      
  }
}

Well, that worked. Ty both. Is the analogRead in the sweep allowing the 'if' statement to intiate? If so, why was lghtMax returning a value but not posMax?

If so, why was lghtMax returning a value but not posMax?

Because the first comparison fills in lightMax and posMax.
After that, they're never touched again.

Is the analogRead in the sweep allowing the ‘if’ statement to intiate?

The if condition is triggered by the state of bttn1, it is not dependent upon the analogRead().

f so, why was lghtMax returning a value but not posMax?

Walk your way through the code step by step, thinking like a computer.

if(lghtMax < lght) {
      lghtMax = lght;
      maxPos = pos;
    }

lghtMax starts at 0, and will be less than the first analogRead and will be set = lght. maxPos will be 0 as pos has not incremented yet. If you never read A0 again, nothing will change.